Here I encountered a cross-domain problem in a mature project that has been built: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Then I personally tested the effective solution:
in the config.js file of the project (the files packaged by each project may be different), look for a js file similar to this one that contains the configuration dev
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
},
Then the key code is to add relevant configuration in the proxyTable object body of this dev object :
proxyTable: {
// 配置跨域
'/api': {
target: "http://xxxx.com", //这里是你所要请求的接口地址
changeOrigin: true, //允许跨域
pathRewrite: {
"^/api": "" //请求的时候用这个api
}
}
},
In this way, the basic configuration is completed, and then stop the project and restart npm run dev to take effect.
Then the calling instance is:
Axios({
url: `/api/xxxx/xxx`, //这个/api就是上面封装好的接口地址,就理解为/api == "http://xxxxx.com",然后后面拼接接口后面的部分
headers: {
"Content-Type": "application/json"},
method: "post" //post/get,
data: data //data为参数请求体
})
In this way, no error will be reported when calling. At present, my problem is solved. There is also a back-end solution, because I am not responsible for the back-end code of this interface, so I have not tried it. Reference link: https://
blog
. csdn.net/sinat_42338962/article/details/104452022
https://ab62.cn/article/1909.html