Skip to content

Instantly share code, notes, and snippets.

@tpai
Last active March 23, 2018 07:52
Show Gist options
  • Save tpai/92b1311964fa5b0c253a2a13d9d0c702 to your computer and use it in GitHub Desktop.
Save tpai/92b1311964fa5b0c253a2a13d9d0c702 to your computer and use it in GitHub Desktop.
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 wit

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment