javascript - Fetch API Post method is not working - Stack Overflow

admin2025-04-19  0

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": "[email protected]",
  "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;
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": "[email protected]",
  "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;
Share Improve this question edited Sep 8, 2017 at 3:50 sideshowbarker 88.6k30 gold badges215 silver badges212 bronze badges asked Sep 8, 2017 at 2:55 Pyae Phyoe SheinPyae Phyoe Shein 13.8k47 gold badges152 silver badges243 bronze badges 3
  • CORS support needs to be added/enabled on the server running on http://localhost:9000. See enable-cors/server.html and developer.mozilla/en-US/docs/Web/HTTP/Access_control_CORS – sideshowbarker Commented Sep 8, 2017 at 3:00
  • 1 @sideshowbarker I've edited my answer and configured CORS in node. – Pyae Phyoe Shein Commented Sep 8, 2017 at 3:06
  • Am I reading in your code correctly that on the node server you only have CORS enabled for the /contact route but that your frontend code is making a request to /api/app/contact? On the node backend do those somehow end up resolving to the same route? To isolate/troubleshoot the problme, Have you tried testing with temporarily enabling CORS for all routes instead of just that one route? – sideshowbarker Commented Sep 8, 2017 at 3:11
Add a ment  | 

2 Answers 2

Reset to default 4

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./package/cors#enabling-cors-pre-flight

Postman is not the same as the browser.

To fix that, you need the server in http://localhost:9000/api/app/contact to return in its headers the CORS header, like this for example Access-Control-Allow-Origin: *

Read here for detailed CORS reference https://enable-cors/server.html

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745077836a283673.html

最新回复(0)