解决跨域 : has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is
一、vue项目下 vue.config.js 文件(get和post请求地址 使用 /api/xxx 替代真实地址)
// vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
publicPath: './'
})
//跨域配置
module.exports = { //node.js 语法
devServer: {
// host: '0.0.0.0',
// port: 80,
// open: true,
proxy: {
'/api': { //识别api
target: 'http://api.baidu.com', //代理的服务器地址涵端口
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
//secure: false, //是否https接口
pathRewrite: { //过滤api字母
'^/api': '' //替换字母
}
}
}
}
}
二、服务端(宝塔例子)
打开部署自己vue项目站点 点击“设置”,弹出站点修改如图弹框,弹框中左侧菜单 “配置文件” 粘贴如下空圈的代码,并修改成自己的api地址

#解决后端api没有代理到的问题直接访问到本服务器ip的问题
location /api{
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://api.baidu.com; #后端接口api地址
index index.html;
}