Nginx solves cross-origin problems and nginx solves cross-origin problems
Here, we use the reverse proxy function of Nginx to solve cross-domain problems. As for what is the reverse proxy of Nginx, please use Baidu or Google. As a reverse proxy server, nginx forwards http requests to another or some servers. By ing a local url prefix to the web server for cross-origin access, you can implement cross-origin access. The browser accesses a url on the same origin server. Nginx detects the url prefix and forwards the http request to the real physical server. Use the rewrite command to remove the prefix. In this way, the real server can process the request correctly and does not know that the request is from the proxy server.
The specific solution is as follows:
Edit in nginx. conf
Server {location/{root html; index index.html index.htm; // Allow cros cross-Origin Access add_header 'access-Control-Allow-origin ''*';} // customize the local path location/apis {rewrite ^. + apis /? (. *) $/$1 break; include uwsgi_params; proxy_pass http://www.lyz.com ;}}
Then, I deployed the project in the nginx html root directory and set the url from http://www.lyz.com/apistest/testto /apis/apistest/test.
For example, the Ajax request is as follows:
$. Ajax ({type: "post", dataType: "json", data: {'parameter ': JSON. stringify (data)}, url: "http://www.lyz.com/apistest/test", async: flag, beforeSend: function (xhr) {xhr. setRequestHeader ("Content-Type", submitType. content_Type); xhr. setRequestHeader ("user-id", submitType. user_id); xhr. setRequestHeader ("role-type", submitType. role_type); xhr. setRequestHeader ("access-token", getAccessToken (). token) ;}, success: function (result, status, xhr) {}, error: function (e) {layerMsg ('request failed, please try again later ')}});
Modify it to the following request:
$. Ajax ({type: "post", dataType: "json", data: {'parameter ': JSON. stringify (data)}, url: "/apis/apistest/test", async: flag, beforeSend: function (xhr) {xhr. setRequestHeader ("Content-Type", submitType. content_Type); xhr. setRequestHeader ("user-id", submitType. user_id); xhr. setRequestHeader ("role-type", submitType. role_type); xhr. setRequestHeader ("access-token", getAccessToken (). token) ;}, success: function (result, status, xhr) {}, error: function (e) {layerMsg ('request failed, please try again later ')}});
Now, the problem is solved.