Javascript CORS:对飞行前请求的响应不';添加标头时无法通过访问控制检查

Javascript CORS:对飞行前请求的响应不';添加标头时无法通过访问控制检查,javascript,node.js,cors,Javascript,Node.js,Cors,express客户端的我的html: 欢迎来到 函数输出(txt){ const pre=document.createElement('pre'); pre.innerText=txt; 文件.正文.附加(预); 返回预处理; } (异步函数(){ const headers=new headers() //headers.append(“授权”,“基本”+btoa('root'+':'+'root')) const{a}=wait fetch('http://localhost:3002

express客户端的我的html:


欢迎来到

函数输出(txt){ const pre=document.createElement('pre'); pre.innerText=txt; 文件.正文.附加(预); 返回预处理; } (异步函数(){ const headers=new headers() //headers.append(“授权”,“基本”+btoa('root'+':'+'root')) const{a}=wait fetch('http://localhost:3002/', { 方法:“GET”, 标题:标题, 模式:“cors”, }).then(r=>r.json()); 输出(`camera:${a}`); })();
我在
http://localhost:3002/
,我添加了
访问控制允许原点

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET,PUT,POST,DELETE');
  res.setHeader("Access-Control-Allow-Headers", "Authorization");
  res.end(JSON.stringify({ a: 1 }));
});


module.exports = router;
它可以工作,我将从
http://localhost:3002/
,并且响应头具有
访问控制允许原点
。 但当我将其添加到fetch.headers:
headers.append(“授权”,“基本”+btoa('root'+':'+'root'))

我会得到这个:

Access to fetch at 'http://localhost:3002/' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
飞行前

HTTP/1.1 200 OK
X-Powered-By: Express
Allow: GET,HEAD
Content-Type: text/html; charset=utf-8
Content-Length: 8
ETag: W/"8-ZRAf8oNBS3Bjb/SU2GYZCmbtmXg"
Date: Thu, 27 May 2021 06:27:19 GMT
Connection: keep-alive
Keep-Alive: timeout=5
在chrome浏览器中,显示了此视图,
临时标题

我不知道为什么,我读过很多文章。
非常感谢您为
get
端点添加CORS响应头,但是错误消息表明飞行前请求(使用选项,而不是get)失败。您需要按照以下方式设置一些内容:

router.options('*', code_to_respond_with_suitable_headers);
也就是说:

不要重新发明轮子

一定要用这个


请务必按照模块说明操作。

我按照您的建议在服务器端使用了它``var cors=require('cors')router.options('*',cors(),function(req,res,next){res.json({a:2});})``而且它有效!但是我可以强制它使用GET方法吗不