需求实现
- 本地请求百度的一个搜索接口,用nginx代理解决跨域
- 思路:前端和后端都用nginx代理到同一个地址8080,这样访问接口就不存在跨域限制
本地页面
- 查询一个百度搜索接口,运行在http://localhost:8035
index.js
const path = '/s?ie=utf-8&mod=1&isbd=1&isid=32E40E4954198269&ie=utf-8&f=8&rsv_bp=1&rsv_idx=2&tn=baidutop10&wd=%E9%98%BF%E9%87%8C%E8%BE%BE%E6%91%A9%E9%99%A2%E8%A3%81%E6%92%A4%E9%87%8F%E5%AD%90%E5%AE%9E%E9%AA%8C%E5%AE%A4&oq=%25E9%2598%25BF%25E9%2587%258C%25E8%25BE%25BE%25E6%2591%25A9%25E9%2599%25A2%25E8%25A3%2581%25E6%2592%25A4%25E9%2587%258F%25E5%25AD%2590%25E5%25AE%259E%25E9%25AA%258C%25E5%25AE%25A4&rsv_pq=aa3000c700059c97&rsv_t=dc43G%2B%2BXaqAS56%2B0UrBoDRNzBFYzNO23OT7ktw83SdWrOCxFOH0i2bYVSOJvWtCQCg&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_btype=t&bs=%E9%98%BF%E9%87%8C%E8%BE%BE%E6%91%A9%E9%99%A2%E8%A3%81%E6%92%A4%E9%87%8F%E5%AD%90%E5%AE%9E%E9%AA%8C%E5%AE%A4&rsv_sid=undefined&_ss=1&clist=&hsug=&f4s=1&csor=0&_cr1=45968';function testNginxFetch() {fetch(`https://www.baidu.com${path}`).then(res => {console.log(res, 'res');})
}testNginxFetch()
- 不出意外的会报cors错误
配置nginx来解决
nginx.conf
server {# 监听端口listen 8080;location / {# 以/开头的请求会被代理到8080proxy_pass http://localhost:8035;}location /s {# 以/s开头的请求也会被代理到8080proxy_pass https://www.baidu.com;}
}
index.js
// 修改请求url,删除域名前缀
fetch(path).then(res => {console.log(res, 'res');
})
启动nginx
cmd输入命令:sudo nginx
查看结果