Home > Article > Operation and Maintenance > How to solve nginx cross-domain problem
Separate the front and back ends, use nginx to solve cross-domain problems
Front end: vue.js nodejs webpack
Backend: springboot
Reverse proxy server: nginx
Idea: Package the front-end code, let nginx point to static resources, and nginx forwards background requests.
1. Package the front-end code:
npm run build
will generate a dist folder. Contains an index.html file and a static folder. Take my local path as an example:
/users/xxx/ideaprojects/webtest/dist
2. Open
nginx.conf in the /usr/local/etc/nginx directory, add the following to the server:
listen 80; #原为8080,避免冲突,更改为80 server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root /users/xxx/ideaprojects/webtest/dist; index index.html; # 此处用于处理 vue、angular、react 使用h5 的 history时 重写的问题 if (!-e $request_filename) { rewrite ^(.*) /index.html last; break; } } # 代理服务端接口 location /api/ { proxy_pass http://localhost:8080/;# 代理接口地址 }
Test
Front end sends request : http://localhost/test, vue-router redirects it to http://localhost/api/demo/1, and the actual access is http://localhost:8080/demo/1.
Send a request directly to the background: access http://localhost/api/demo/1, the actual access is: http://localhost:8080/demo/1
Thinking about content expansion:
1).
# Proxy server interface
location /api/ { proxy_pass http://localhost:8080/;# 代理接口地址 }
The proxy interface address only reaches 8080, then it will automatically add the name of the background project? ? ? For example, the interface is http://148.70.110.87:8080/project name/method name. . .
2).js is requested like this. nginx is configured according to your above, but the request error is http://148.70.110.87/api/index2 404 (not found)
axios.post('/api/index2') .then( (response) =>{ console.log(response); }) .catch( (error)=> { console.log(error); });
3). The third step is testing. I really can’t understand it. It would be great if there is relevant code.
The above is the detailed content of How to solve nginx cross-domain problem. For more information, please follow other related articles on the PHP Chinese website!