美文网首页
lighthttpd服务实现跨域请求

lighthttpd服务实现跨域请求

作者: 李牧敲代码 | 来源:发表于2018-11-19 17:54 被阅读0次

    最近公司的一个项目需求需要实现请求跨域,服务端用的lighttpd server。于是开始各种查资料,终于搞定了,现在总结如下:

    1. 编辑配置文件/conf/lighttpd.conf

    vi /conf/lighttpd.conf 
    

    这是我的配置文件,在“setenv.add-response-heade”中加入"Access-Control-Allow-Origin" => ""和"Access-Control-Allow-Headers" => ""

    $HTTP["url"] =~ "\.js$|\.html$|\.css$|\.png$|\.woff$|\.jpg$|^/$" {
    setenv.add-response-header += ( "Content-Encoding" => "gzip","X-Frame-Options" => "SAMEORIGIN","Access-Control-Allow-Origin" => "*","Access-Control-Allow-Headers" => "*")
    
    $HTTP["url"] =~ "^/api" {                      
    setenv.add-response-header += ( "Cache-Control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0", "Access-Control-Allow-Origin" => "*","Access-Control-Allow-Headers" => "*")
    }  
    
    敲黑板啦,这里如果资源文件和请求都需要跨域都得加上"Access-Control-Allow-Origin" => "*"。PS:我就是资源文件加了:
    $HTTP["url"] =~ "\.js$|\.html$|\.css$|\.png$|\.woff$|\.jpg$|^/$" {
    setenv.add-response-header += ( "Content-Encoding" => "gzip","X-Frame-Options" => "SAMEORIGIN","Access-Control-Allow-Origin" => "*")
    
    而接口没加:
    $HTTP["url"] =~ "^/api" {                      
    setenv.add-response-header += ( "Cache-Control" => "no-store, no-cache, must-revalidate, post-check=0, pre-check=0", "Access-Control-Allow-Origin" => "*")
    }
    
    导致折腾了一下午!!

    2. 重启lighthttpd

    /etc/init.d/lighttpd.sh restart -f /conf/lighttpd.conf
    

    3. 测试

    写一个html文件,用apache 启动

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="./jquery.js"></script>
    </head>
    <body>
    <script>   
    jQuery.ajax({
        type: "GET",
        url: "https://192.168.21.108/api/oem_flag",
        timeout: 30000,
        success: (data) => {
            console.log(data)
        },
        error: () => {
    
        }
    })           
    </script>
    </body>
    </html>
    

    查看控制台

    图1.1

    4.成功。。。

    相关文章

      网友评论

          本文标题:lighthttpd服务实现跨域请求

          本文链接:https://www.haomeiwen.com/subject/rluafqtx.html