在localhost上运行时,CORS出现Firebase错误

时间:2018-05-06 20:45:45

标签: node.js reactjs firebase cors

运行项目时出现以下错误。

  

无法加载   https://us-centralx-xxx.cloudfunctions.net/xxx:   对预检请求的响应没有通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' 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
    });
});

3 个答案:

答案 0 :(得分:2)

在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并根据您的需要对其进行配置。

答案 1 :(得分:0)

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
   })
)

答案 2 :(得分:0)

当我意识到没有将功能部署到Firebase时,我遇到了这个问题并遇到了同样的错误。部署它可以停止该错误。如此愚蠢,但要犯同样的错误并不难。