Vue CLI devServer.proxy需在vue.config.js顶层配置,target必须带http://协议,路径匹配用^/api锚定,并用pathRewrite去除前缀;Nginx部署时需配置location /api/反向代理;后端CORS需显式允许前端端口并处理credentials。

Vue CLI 的 devServer.proxy 怎么写才不 404
代理配置写错,前端发请求直接 404 或返回 HTML 页面,不是后端接口响应。根本原因是路径重写没对齐、目标地址没带协议、或代理规则被 Vue Router history 模式干扰。
实操建议:
立即学习“Java免费学习笔记(深入)”;
-
devServer.proxy必须写在vue.config.js顶层,不是configureWebpack里 - 目标地址(
target)必须带http://或https://,比如http://localhost:8080,漏了协议会静默失败 - 路径匹配要加
^/api开头锚定,避免/api/user被误匹配成/apisomething - 后端接口实际路径是
/user/list,但前端调用/api/user/list,那就要用pathRewrite: { '^/api': '' }去掉前缀
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: { '^/api': '' }
}
}
}
}
Java 后端为什么收不到 Origin 头、CORS 报错
Vue 代理生效后,浏览器发的是 http://localhost:8080/api/user 请求,但后端没配 CORS,或者只放行了 http://localhost:8080 却没放行 http://localhost:8081(Vue 默认端口),结果预检请求(OPTIONS)被拒,控制台报 No 'Access-Control-Allow-Origin' header。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- Spring Boot 项目优先用
@CrossOrigin注解,加在 Controller 类或方法上,比全局配置更可控 - 如果用全局配置,确认
WebMvcConfigurer中的addCorsMappings方法里,allowedOrigins包含http://localhost:8081(Vue 端口),别只写*—— 它不支持带凭证(cookie)的请求 - 若需传 cookie,前后端都要设:前端
axios.defaults.withCredentials = true,后端allowedOrigins不能为*,且必须显式设置allowCredentials(true)
打包后部署到 Nginx,API 请求变成 404 怎么修
开发时靠 Vue CLI 代理没问题,但 npm run build 后静态资源扔进 Nginx,代理就失效了。此时所有 /api 请求都由 Nginx 直接处理,而它根本不知道该转给谁,自然 404。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 前端请求地址别写死
http://localhost:8080/api,统一用相对路径,如/api/user - Nginx 配置里加 location 块,把
/api开头的请求反向代理到 Java 后端:location /api/ { proxy_pass http://127.0.0.1:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } - 注意
proxy_pass末尾的/:有它会剥离/api/前缀;没它会原样转发,后端得监听/api/**
Java 后端接口返回 JSON,但前端拿到的是乱码或空白
常见于 Spring Boot 返回中文字段时,响应头没设 Content-Type: application/json;charset=UTF-8,浏览器按 ISO-8859-1 解析,中文全变 。
实操建议:
立即学习“Java免费学习笔记(深入)”;
- 检查 Controller 方法是否用了
@ResponseBody或@RestController,否则 Spring 不自动序列化 - 确保
application.properties里有:spring.http.encoding.charset=UTF-8 spring.http.encoding.force=true spring.http.encoding.enabled=true
- 如果用 Jackson,确认没有手动 new
ObjectMapper并忽略字符集设置;默认 Spring Boot 的MappingJackson2HttpMessageConverter已配 UTF-8










