2017-02-17 34 views
2

我有一个反应的应用程序,并取回调用的API如下:然而如何使用抓取来发布与内容类型的应用程序/ JSON

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调用以执行所需的预执行请求以使其允许应用程序/ 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); 
}); 

回答

2

之前定义你的路由。声明

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中,将检查服务器上可用方法的请求。即在选项请求。当您获得成功的回复时,您将能够发送请求。

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

+0

快速的人,工作!谢谢:) – Wayneio

+0

你可以标记为帮助他人的正确答案。当然是 –

+0

- 我需要等8分钟 – Wayneio

相关问题