NodeJS 在本地主机上运行时,CORS出现Firebase错误

mfpqipee  于 2023-04-20  发布在  Node.js
关注(0)|答案(4)|浏览(176)

我在运行项目时遇到以下错误。
无法加载https://us-centralx-xxx.cloudfunctions.net/xxx:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“http://localhost:3000”。响应的HTTP状态代码为500。
在阅读了许多SO帖子后,我发现了以下解决方案,其中我需要添加Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-Headers

const HEADERS = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin':  'http://localhost:3000/',
    'Access-Control-Allow-Methods': 'POST',
    'Access-Control-Allow-Headers': 'X-Requested-With,content-type'
};

但是,错误仍然存在。我该如何解决这个问题?

更新

exports.uploadFile = functions.https.onRequest((req, res) => {
        res.setHeader("Access-Control-Allow-Origin", "*");

        res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');

    res.status(200).json({
        message: req.body
    });
});
nwwlzxa7

nwwlzxa71#

在你的Node.js服务器中设置适当的头文件以允许受控的CORS请求:

app.use((req, res, next) => {
  const origin = req.headers.origin;
  // arrayOfValidOrigins is an array of all the URL from where you want to allow 
  // to accept requests. In your case: ['http://localhost:3000'].
  // In case you want to accept requests from everywhere, set:
  // res.setHeader('Access-Control-Allow-Origin', '*');
  if (arrayOfValidOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  // Here allow all the HTTP methods you want
  res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,HEAD,PUT,OPTIONS');
  // Here you allow the headers for the HTTP requests to your server
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  // Method to reference to the next Node.js function in your flow
  next();
});

另一个选择是使用Express.js CORS package并根据您的需要进行配置。

8mmmxcuj

8mmmxcuj2#

当我意识到我没有将函数部署到Firebase时,我遇到了这个问题,并得到了同样的错误。部署它阻止了错误。太傻了,但犯同样的错误并不难。

zaq34kh6

zaq34kh63#

import * as cors from 'cors'

const corsHandler = cors({origin: true})

export const myFunc = functions.https.onRequest(async (req: Request, res: Response) => {
   corsHandler(req, res, () => {
     // Do your work here
   })
)
gjmwrych

gjmwrych4#

尝试从Firebase函数检查日志。在我的情况下,Chrome Devtools显示CORS错误:

"severity": "ERROR",
"message": "Error: No Firebase ID token was passed as a Bearer token 
in the Authorization header. Make sure you authorize your request by 
providing the following HTTP header: Authorization: Bearer <Firebase ID Token>

作为解决方案,缺少Barear令牌是需要解决的问题。
一定要检查日志。

相关问题