【问题标题】:Blocked by CORS only on post request [duplicate]仅在发布请求时被 CORS 阻止 [重复]
【发布时间】:2021-03-10 11:20:27
【问题描述】:

当我向我的 api 发出请求时,chrome 会阻止我请求内核的原因。在我的 firebase 云功能上,我添加了 response.set('Access-Control-Allow-Origin','*'); (axios get中的xxxxxx只是为了隐藏请求url)

export const getApproximateAddress = functions.https.onRequest(async(request, response)=>{
 try{
     response.set('Access-Control-Allow-Origin','*');
     response.set('Access-Control-Allow-Methods','GET, POST, PATCH, PUT, DELETE, OPTIONS');
     let data = JSON.parse(request.body);
     let lat = "";
     let lng = "";
     let hasCoords = false;
     if( data.lat !== undefined && data.lng !== undefined){
         lat = data.lat;
         lng = data.lng;
         hasCoords = true;
     }
     let place = data.place;
     let result;
     if(hasCoords){
         result = await axios.get(`xxxxxxxx`);
         console.log("hehe");
     }else{
         result = await axios.get(`xxxxxxxx`);
     }
     if(result.status !== 200){
        response.status(result.status).send(result.data);
     }else{
        console.log(result.data.features);
        response.status(200).send(result.data.features);
     }
  }catch(error){
     response.status(500).send(error);
 }

});

然后在我的 Angular 应用程序中,我发出这样的 http 发布请求

searchLoation(query:any):Observable<any>{
  const url = 'https:XXXXXXXX/getApproximateAddress';
  return this.http.post(url,{place:query},{
    observe: 'body'
  });
}

url 与请求来自的域不同。

当我在邮递员中测试所有内容时,一切正常......

【问题讨论】:

  • 您是否允许 CORS 请求?
  • 您没有在函数中正确实现 CORS。如果您使用 CORS 中间件,如this other question所示,会更容易。 stackoverflow.com/questions/42755131/…
  • 在我的函数请求中,我添加了这个 response.set('Access-Control-Allow-Origin','*'); (参考第一个代码 sn -p )
  • @DougStevenson 你是对的,我之前用来处理 cors 的方法不正确,我实现了 const cors = require('cors')({ origin: true });并将我的函数体包裹在 cors(req, res, () => { function boy here });它奏效了
  • 任何人都知道如何用我找到的解决方案更新这个问题,以便任何有相同问题的人都可以使用它吗?

标签: angular firebase google-cloud-functions


【解决方案1】:

您需要在您的服务器上允许 CORS(在您的云函数 API 中)。可能是这样的,具体取决于您的 API 内置。CORS 始终需要在服务器上设置,标头通常不会产生影响。下面以 node.js 解决方案为例。你需要安装 cors 库

import * as cors from 'cors'

const app = express()

app.use(
  cors({
    origin: true,
  }),
)

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 2017-05-31
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2020-08-16
    • 2022-11-01
    • 2019-09-30
    相关资源
    最近更新 更多