React跨域访问 API
前端开发时,会经常遇到这一题: 跨域,默认情况下,浏览器时禁止的.
假设: web 127.0.0.1:8080 ; API server: 127.0.0.1:3000
如果你在react中用 axios请求: /api/sentences, 浏览器就会报类似错误
下面演示在mac上如何用nginx方向代理
目的: 用react获取api: http://tjxbt.cn/api/sentences
分析:
- 前端url: http://127.0.0.1:8080
- 后端api: http://tjxbt.cn/api/sentences
1. 用8080 http static server 启动 yarn build后的react页面
yarn build
cd build
http-server # 默认在8080启动,可用 -p 参数指定 port
2. nginx配置
假设已安装好nginx
mkdir -p /usr/local/etc/nginx/servers
cd /usr/local/etc/nginx/servers
vim http://tjxbt.cn-80.conf
server {
listen 80;
server_name 127.0.0.1;
location /{
proxy_pass http://127.0.0.1:8080;
}
location /api{
proxy_pass http://tjxbt.cn;
}
location ~ /.well-known {
allow all;
}
client_max_body_size 50m;
}
sudo nginx -t
sudo nginx -s reload
当访问 127.0.0.1 的时候就可以访问到 api