Calling api within Create-react-app

Most of frontend application need to fetching data from server side to display data. After some try and error this is how I developed and deployed react application

Development - proxy for stay away from CORS

Update: React supports a better way by using proxy. I pushed the link in the bottom of this post.

The most painful things is CORS, at the first time I always need to inject Access-Control-Allow-Origin to the header for supporting calling api from localhost.

Using the proxy like this you can call the api from /api/v1

1
2
3
4
5
6
7
8
9
10
11
12
app.use(
'/api/v1',
proxy({
target: 'http://xx.yy.zz.zzz/',
changeOrigin: true,
onProxyReq(proxyReq, req) {
if (proxyReq.getHeader("origin")) {
proxyReq.removeHeader("origin")
}
}
})
);

Every requests to /api/v1 will be forwarded to http://xx.yy.zz.zzz/api/v1.
Be notice how the path will be applied. The more information can be found here.

Deployment - using nginx for serving and forward api

I used an nginx instance to serve static file and forward the api. The configuration can be like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// nginx.conf

server
{
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}

location /api/v1/ {
proxy_pass http://xx.yy.zz.zzz/api/v1/
}
}

Every requests will be forwarded also. Do notice of the path, that’s a slight difference between 2 methods.

Tell me if you have any better ideas.

Update: this is the better way to make the request, by using proxy.

  • Copyrights © 2017-2024 Bach Nguyen

请我喝杯咖啡吧~

支付宝
微信