This is the second day of my participation in Gwen Challenge

The business scenario

In a development scenario with a separate front and back end, we have two ways of releasing the production environment for the front end:

  • Inherit packaging with the back end
  • Using a Web Server

When using the latter, you encounter cross-domain requests

This article details how to use Nginx as a Web server while handling cross-domain issues

plan

Use Nginx as the Web server

First, download the corresponding program package from the official website based on the server operating system

The decompressed directory structure is as follows:

HTML (default service file address) and conf(configuration file directory) are more important

Without modifying the configuration file, we move the front-end compiled file to the HTML directory, run nginx.exe, and a simple Web service is built

Web Service Configuration

Conf /nginx.conf

http { server { listen 80; server_name localhost; location / { root html; index index.html; }}}Copy the code

Note the following important configuration meanings:

  • Server: A server represents a virtual node
  • Server. listen: listening port
  • Server. server_name: indicates the domain name, for examplelocahost:80andwww.baidu.com:80It’s totally different
  • Location: location mode
  • Location. root: the root directory of the location mode content. When the value is relative path, the automatic completion of the directory where nginx is located. The default web path is HTML because of the configuration above/Locate the{nginx}/htmlIn the
  • Location. index: home page file

If we want to publish /app/koala-ui/dist as a Web service using Nginx, we can configure it like this:

http { server { listen 8000; server_name localhost; location / { root /app/koala-ui/dist; index index.html; }}}Copy the code

For more loaded configurations such as variable/path overrides, refer to the official documentation

To solve the cross domain

Our Koala-UI is already accessible using localhost:8000, but the address of the background interface is localhost:9999/ API

Conf /nginx.conf add a location proxy to the interface:

http { server { listen 8000; server_name localhost; Location/API {proxy_pass http://127.0.0.1:9999; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location / { root /app/koala-ui/dist; index index.html; }}}Copy the code

There are a few things to emphasize:

  • The value of the proxy_passhttp://127.0.0.1:9999andhttp://127.0.0.1:9999/isIs there a difference in the, the corresponding addresses of proxy/API /test are respectivelyhttp://127.0.0.1:9999/api/testandhttp://127.0.0.1:9999/test
  • proxy_set_header X-Real-IP $remote_addrandproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_forSetting isThe necessary, the purpose is so that the server canObtain the real IP address of the user
  • location /{... }Be sure toIn the last