先配置一个vue.config.js在根目录下
module.exports = {
devServer: {
open: true,
host: 'localhost',
port: 19999,
proxy: {
'/api': {
target: 'http://localhost:18999',
changeOrigin: false,
pathRewrite: {
'^/api': ''
},
headers: {
'Access-Control-Allow-Origin': '*'
}
}
}
}
}
首先,host是开启的ip地址,port是断开,npm run serve 启动之后就是用这个ip和地址跑起来。
接着proxy下的,当有请求是以/api/开头的就会默认转发到target下,这个时候有一个重写url,就是pathRewrite,这里的意思是将路径上的"api"字符替换为"",也就是空
比如请求的是:
http://localhost:19999/api/gethello
转发之后的url是
http://localhost:18999/gethello
如果是使用的axios,不要配置baseUrl,不要会失效
import axios from 'axios';
let http = axios.create({
// baseURL: 'http://localhost:18999/',
withCredentials: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',"Access-Control-Allow-Origin": "*"},
});
export default http;