tpai
3/23/2018 - 7:49 AM

In out cors

In the present, web services almost build based on microservice architecture, separate front end node app and back end api, this will cause cors issue while developing and distributing production, that's go through some basic solution for dealing with cors.

CORS solution

In the present, web services almost build based on microservice architecture, separate front end node app and back end api, this will cause cors issue while developing and distributing production, that's go through some basic solution for dealing with cors.

API server CORS enabled

By default json-server is launch with cors enabled, so directly fetch data from API server.

API server CORS disabled

Launch json-server with --no-cors=true argument.

Develop mode (create-react-app)

Set proxy setting in package.json

"proxy": "http://localhost:8888"

Develop mode (webpack-dev-server)

Set proxy setting in webpack.config.js

proxy: {
  "/api": "http://localhost:8888"
}

Ref: https://webpack.js.org/configuration/dev-server/#devserver-proxy

Then Revise fetch url to relative path.

fetch("http://localhost:8888/api/posts") => fetch("/api/posts")

Production mode

Use nginx as reverse proxy server to do load balance.

Get your host ip first

$ ipconfig getifaddr en4

nginx.conf

events {}

http {
  upstream api {
    server [host-ip]:8888;
  }

  upstream node {
    server [host-ip]:5000;
  }

  server {
    listen       80;
    server_name  127.0.0.1;

    location /api/ {
      proxy_pass http://api;
    }

    location / {
      proxy_pass http://node;
    }
  }
}

Ref: Config Validator

Launch nginx server with docker

docker run -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf -p 80:80 nginx

Reference