Fetch API Post方法无效 [英] Fetch API Post method is not working

查看:107
本文介绍了Fetch API Post方法无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  fetch('http:// localhost:9000 / api / app / contact',{
method:'POST',
header:{
'content-type':'application / json'
},
body:JSON.stringify({
email:this.state.email,
contactNumber:this。 state.phone,
查询:this.state.msg
})
})
.then(function(res){return res.json()})
。然后(功能(数据){
alert('我们会尽快与您联系')
});

当我在编码上面渲染时,我遇到了以下错误:


无法加载



以下代码是来自 Postman 的发布请求。

  var data = JSON.stringify({
email:test@gmail.com,
contactNumber:0123456789,
查询:测试
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener(readystatechange,function(){
if(this.readyState === 4){
console.log(this.responseText);
}
});

xhr.open(POST,http:// localhost:9000 / api / app / contact);
xhr.setRequestHeader(content-type,application / json);
xhr.setRequestHeader(cache-control,no-cache);
xhr.setRequestHeader(postman-token,d5e08b69-5f0f-8193-e021-e2c3b1bfe1a3);

xhr.send(数据);

在NodeJS服务器端,我已经在后端使用CORS。

  var express = require('express'),
controller = require('。/ app.controller'),
router = express .Router(),
cors = require('cors');

var issue2options = {
origin:true,
methods:['POST'],
凭证:true,
maxAge:3600
};

router.post('/ contact',cors(issue2options),controller.sendContactForm);
module.exports = router;


解决方案

您需要添加显式选项处理 CORS预检浏览器自行发送:

  app.options('/ contact',cors(issue2options)); //启用预检OPTIONS 
router.post('/ contact',cors(issue2options),controller.sendContactForm);

参见 https://www.npmjs.com/package/cors#enabling-cors-pre-flight


fetch('http://localhost:9000/api/app/contact', {
    method: 'POST',
    headers: {
        'content-type': 'application/json'
    },
    body: JSON.stringify({
        email: this.state.email,
        contactNumber: this.state.phone,
        enquiry: this.state.msg
    })
})
.then(function(res) { return res.json() })
.then(function(data) {
    alert('We will contact you shortly') 
});

When I render above coding, I've encountered following error:

Failed to load http://localhost:9000/api/app/contact: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

But when I tried with postman, it's successfully working. Please help me, is there any code missing in my fetch api.

Following is postman POST request and code.

following code is Post request from Postman.

var data = JSON.stringify({
  "email": "test@gmail.com",
  "contactNumber": "0123456789",
  "enquiry": "Testing"
});

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:9000/api/app/contact");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "d5e08b69-5f0f-8193-e021-e2c3b1bfe1a3");

xhr.send(data);

In NodeJS server side, I've already CORS in backend.

var express = require('express'),
    controller = require('./app.controller'),
    router = express.Router(),
    cors = require('cors');

var issue2options = {
  origin: true,
  methods: ['POST'],
  credentials: true,
  maxAge: 3600
};

router.post('/contact', cors(issue2options), controller.sendContactForm);
module.exports = router;

解决方案

You need to add explicit OPTIONS handling for CORS preflights that browsers send on their own:

app.options('/contact', cors(issue2options)); // enable preflight OPTIONS
router.post('/contact', cors(issue2options), controller.sendContactForm);

See https://www.npmjs.com/package/cors#enabling-cors-pre-flight

这篇关于Fetch API Post方法无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆