在这里我是在一个已经搭建好的成熟项目中遇到的跨域问题:Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
然后我自己亲测有效的方案是:
在项目的config.js文件(每个项目封装的文件可能不一样),就找跟这个类似的包含配置dev的js文件
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
},
// Various Dev Server settings
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 80, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
然后重点代码是在这个dev对象的proxyTable对象体里面加入相关配置:
proxyTable: {
// 配置跨域
'/api': {
target: "http://xxxx.com", //这里是你所要请求的接口地址
changeOrigin: true, //允许跨域
pathRewrite: {
"^/api": "" //请求的时候用这个api
}
}
},
这样基本配置就完成了,然后把项目停掉重新npm run dev就生效了
接着调用实例就是:
Axios({
url: `/api/xxxx/xxx`, //这个/api就是上面封装好的接口地址,就理解为/api == "http://xxxxx.com",然后后面拼接接口后面的部分
headers: {
"Content-Type": "application/json"},
method: "post" //post/get,
data: data //data为参数请求体
})
这样调用的时候就不会报错了,目前我的问题是解决了,还有一种后端的解决方案,因为这个接口的后端代码不是我负责,所以我没有尝试
参考链接:
https://blog.csdn.net/sinat_42338962/article/details/104452022
https://ab62.cn/article/1909.html