nginx's instance method for solving cross domain problems
- 2020-05-17 07:41:59
- OfStack
The front and rear ends are separated and nginx is used to solve cross-domain problems
Front end: vue js + nodejs + webpack
Background: SpringBoot
Reverse proxy server: nginx
Idea: package the front-end code so that nginx points to the static resource, and nginx forwards the backend request.
1. Package the front-end code:
npm run build
An dist folder is generated. Contains 1 index.html file and 1 static folder. The path takes my local as an example:
/Users/xxx/ideaProjects/webtest/dist
2, open the
/ usr local etc/nginx directory nginx. conf, added in the server is as follows:
listen 80; # originally 8080 , to avoid conflict, change to 80
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root /Users/xxx/ideaProjects/webtest/dist;
index index.html;
# This is used for processing Vue , Angular , React use H5 the History when The problem of rewriting
if (!-e $request_filename) {
rewrite ^(.*) /index.html last;
break;
}
}
# Proxy server interface
location /api/ {
proxy_pass http://localhost:8080/;# Proxy interface address
}
test
Front end sends the request: http: / / localhost test, http vue - router to redirect it to: / / localhost api/demo / 1, the actual access is http: / / localhost: 8080 / demo / 1.
Directly to the backend sends a request: visit http: / / localhost api/demo / 1, the actual access is: http: / / localhost: 8080 / demo / 1
Content expansion thinking:
1).
Proxy server interface
location /api/ {
proxy_pass http://localhost:8080/;# Proxy interface address
}
Proxy interface address only to 8080, then he will automatically add the name of the background project?? Such as interface http: / / 148.70.110.87:8080 / project name/method name...
Is such a request, 2). js nginx is according to your configuration, but the request error 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). Your third step, test, really can't understand if you can have the relevant code