cors 跨域
// const allow_origin = ['localhost:3000', 'www.xxxxxx.com']
const whiteList = ["http://localhost:8080", "http://localhost:8081","http://112.74.111.xxx:20200"]
function cors(req, res, next) {
// 设置响应头
// Access-Control-Allow-Origin
// Access-Control-Allow-Methods
// Access-Control-Allow-Headers
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
// res.header("Access-Control-Allow-Methods","PUT,POST,GET,PATCH,DELETE,OPTIONS");
// console.log('Origin:',req.get('host'));
// 获取请求者的域名
// if (allow_origin.includes(req.get('host'))) {
// res.set({
// "Access-Control-Allow-Origin": "http://localhost:8081",
// "Access-Control-Allow-Headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With",
// "Access-Control-Allow-Methods": "PUT,POST,GET,PATCH,DELETE,OPTIONS",
// "Access-Control-Allow-Credentials": true
// })
// // 跨域请求CORS中的预请求
// if (req.method == "OPTIONS") {
// res.sendStatus(200); /*让options请求快速返回*/
// } else {
// next();
// }
// } else {
// res.send(401);
// }
// 白名单允许跨域
const origin = req.get('Origin')
if (whiteList.includes(req.get('Origin'))) {
res.set({
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With",
"Access-Control-Allow-Methods": "PUT,POST,GET,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Credentials": true
})
// 跨域请求CORS中的预请求
if (req.method == "OPTIONS") {
res.sendStatus(200); /*让options请求快速返回*/
} else {
next();
}
} else {
res.send(401);
}
}
module.exports = cors;
vue中的 axios 上线问题处理
import axios from "axios";
const baseUrl = process.NODE_ENV === 'development' ? 'http://localhost:3000' : 'http://112.74.111.xxx:20020'
const request = axios.create({
baseURL: baseURL + "/api",
// baseURL: 'http://localhost:3000/api',
// 相关Session等处理 比如图形验证码
withCredentials: true
})
export default request;
vue.config.js配置文件中
devServer: {
open: true, //浏览器自动打开页面
host: "0.0.0.0", //如果是真机测试,就使用这个IP
port: 8911,
https: false,
hotOnly: false, //热更新(webpack已实现了,这里false即可)
proxy: {
//配置跨域
'/api': {
target: "http://112.74.111.183:3000/api",
ws:true,
changOrigin:true,
pathRewrite:{
'^/api':'/'
}
}
}
}
//调用
this.$http.get('/api/order/getOrder')
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err.data.message);
});