背景
前端仔试过了:node跨域、vue Proxy跨域、jq跨域、后台大佬协助跨域,
这次跨域就是要用 nginx !!!其他我不管!
html代码
let res = fetch('http://localhost:8088/follow').then(res=>{
console.log(res)
})
node,server代码
const http = require('http')
const server = http.createServer((req,res)=>{
console.log(req)
res.writeHead(200,{'Content-Type':'text-plain'});
res.end('Hello Node');
})
server.listen(3333, () => {
console.log(`server running at 3333`)
})
nginx配置
location /follow/ {
proxy_pass http://localhost:3333;
}
或者
location /follow/ {
proxy_pass http://127.0.0.1:3333;
}
报错
Access to XMLHttpRequest at http://localhost:8088/follow' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
现象
不管怎么调,
- 修改fetch的url
- 修改nginx正则匹配规则
- 给location添加配置头
都无法正确完成nginx跨域。人生很灰暗,感觉自己像是进入了死胡同。
到底是什么原因呢?难道我们一遍遍的试就没有一次是对的吗?
原因
少加了一条代码:add_header 'Access-Control-Allow-Origin' '*';
server {
listen 8088;
server_name localhost;
location /follow/ {
add_header 'Access-Control-Allow-Origin' '*';
proxy_pass http://127.0.0.1:3333/;
}
}
加完后就能解决!!!
如果还没解决呢?继续看
使用nginx要点:
- nginx监听端口,一定要未被占用。
- nginx监听端口可以随意设置,但请求url的主机名、端口号要一致,一变都变。
- 此时,可以跟 远程(后台)接口地址不一
分析:
能解决的代码知识都在这了,如果还没走通:
- 重启nginx,看看运行有没有问题。
- 比对接口、主机名是否一致。
nginx小贴士:
// 启动
start nginx
// 或者直接点击
nginx.exe
// 重启
nginx -s reload
// 立即停止
nginx -s st
Q:方法你都懂,为什么还是会报错?
A:懂方法可以确保大方向没问题,报错基本上是不熟悉,理解不到位造成的 漏、忘。
结语:
说实话,'Access-Control-Allow-Origin' '*',这句代码我知道,node服务会需要,但是。。。唉。
加它是从后台层面解决跨域的方法,我只记住了 后台 却完全忘记了 服务器 天真的以为nginx很强大解决跨域也需要它吗?太尴尬了,太浅显了,太年轻了。
本文暂时没有评论,来添加一个吧(●'◡'●)