Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

javascript - Fetch API Post method is not working

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.

enter image description here

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...