【问题标题】:How to use fetch to post with content-type of application/json如何使用 fetch 发布内容类型为 application/json
【发布时间】:2017-07-06 19:44:40
【问题描述】:

我有一个对 API 进行 fetch 调用的 react 应用程序,如下所示:

 postForm(state) {
    var formData = state.formData;
    return fetch('http://localhost:3000/api/V0.1/formSubmit', {method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(formData)})
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson);
      return null;
    })
    .catch((error) => {
      console.error(error);
    });
  }

但是,它被 CORS 阻止,因为规范指出 application/json 是非标准内容类型。

但是,我不确定如何修改我的 fetch 调用以执行所需的飞行前请求以使其允许 application/json。

API 调用是:

app.post("/api/v0.1/formSubmit", function(req, res) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', '*');
  var formData=req.body;
  console.log(formData);
  res.status(200).json(formData);
});

【问题讨论】:

    标签: json node.js cors fetch


    【解决方案1】:

    在定义您的路由之前。声明

    app.use(function(req, res, next) {
            var oneof = false;
            if(req.headers.origin) {
                res.header('Access-Control-Allow-Origin', req.headers.origin);
                oneof = true;
            }
            if(req.headers['access-control-request-method']) {
                res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
                oneof = true;
            }
            if(req.headers['access-control-request-headers']) {
                res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
                oneof = true;
            }
            if(oneof) {
                res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
            }
    
            // intercept OPTIONS method
            if (oneof && req.method == 'OPTIONS') {
                res.send(200);
            }
            else {
                next();
            }
        });
    

    在 CORS 中,检查请求以获取服务器上的可用方法。即在 OPTIONS 请求中。当您收到成功的响应后,您就可以发送请求了。

    您也可以为特定页面启用 CORS。在这里学习https://github.com/expressjs/cors

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 2023-03-28
      • 2019-03-01
      • 1970-01-01
      • 2021-04-30
      • 2011-08-09
      相关资源
      最近更新 更多