Vue.js跨域請求配置、Node.js設置允許跨域

Vue跨域配置

在Vue項目目錄中打開config/index.js,在proxyTable中添寫如下代碼:

proxyTable: { 
  '/api': {  //使用"/api"來代替"http://  你的地址(http://127.0.0.1:3000)" 
    target: 'http:// 你的地址 ',    //源地址 
    changeOrigin: true,    //改變源 
    pathRewrite: { 
      '^/api': 'http://  上面的地址,或者空著不寫'     //路徑重寫 
      } 
  } 
}

Node設置跨域 , 在你的app.js里

設置允許所有域名跨域:

app.all("*",function(req,res,next){
    //設置允許跨域的域名,*代表允許任意域名跨域
    res.header("Access-Control-Allow-Origin","*");
    //允許的header類型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允許的請求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options'){
        res.send(200);  //讓options嘗試請求快速結束
    }else{
        next();
    }
}

設置允許指定域名“http://xxxxxx”跨域:

app.all("*",function(req,res,next){
    //設置允許跨域的域名
    res.header("Access-Control-Allow-Origin","http://xxxxxx");
    //允許的header類型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允許的請求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options'){
        res.send(200);
    } else{
        next();
    }
}

設置允許多個域名跨域:

app.all("*",function(req,res,next){
    //判斷請求頭
    if( req.headers.origin.toLowerCase() == "http://xxxxxx"
        || req.headers.origin.toLowerCase() =="http://127.0.0.1" ) {
        res.header("Access-Control-Allow-Origin", req.headers.origin);
    }
    //允許的header類型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允許的請求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options'){
        res.send(200);
    } else{
        next();
    }    
}

如果允許的域名較多,可以將允許跨域的域名放到數組當中:

app.all("*",function(req,res,next){
    var orginList=[
        "http://127.0.0.1",
        "http://www.xxxxxx.com",
        "http://www.baidu.com",
        "http://www.alibaba.com",
        "http://www.qq.com"
    ]
    if(orginList.includes(req.headers.origin.toLowerCase())){
        res.header("Access-Control-Allow-Origin",req.headers.origin);
    }
    //允許的header類型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允許的請求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options'){
        res.send(200);
    } else{
        next();
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。