Nginx配置跨域-只有暴漏了问题,才能解决问题

背景
前端仔试过了: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 {listen8088;server_namelocalhost;location /follow/ {add_header 'Access-Control-Allow-Origin' '*';proxy_pass http://127.0.0.1:3333/;}}
【Nginx配置跨域-只有暴漏了问题,才能解决问题】加完后就能解决?。。?
能解决的代码知识都在这了,如果还没走通:
重启nginx , 看看运行有没有问题 。比对接口、主机名是否一致 。
nginx小贴士:
// 启动start nginx// 或者直接点击nginx.exe// 重启nginx -s reload// 立即停止nginx -s st
Q:方法你都懂,为什么还是会报错?
A:懂方法可以确保大方向没问题,报错基本上是不熟悉,理解不到位造成的 漏、忘 。
结语:
说实话,'Access-Control-Allow-Origin' '*' , 这句代码我知道,node服务会需要,但是 。。。唉 。
加它是从后台层面解决跨域的方法,我只记住了 后台 却完全忘记了 服务器 天真的以为nginx很强大解决跨域也需要它吗?太尴尬了,太浅显了,太年轻了 。
以上就是朝夕生活(www.30zx.com)关于“Nginx配置跨域-只有暴漏了问题,才能解决问题”的详细内容,希望对大家有所帮助!

猜你喜欢