0

I'm using fetch web API to send a post method request from reactJS to express NodeJS server both on localhost with different ports.

Client Fetch API

fetch("http://localhost:8081/test", 
{
            method: "post",
            mode:"no-cors",
            headers: {
                'Content-Type': 'application/json',
            },        
            body: JSON.stringify({
                username : "John Doe",
                password : "It's a secret"
            })
}).then(function(response)
{
            if(response.ok)
            {
                return response.json();
            }else
            {
                console.log(response)
            }
}).then(function(body) { console.log(body); }).catch((error) => { console.log(error) });

Server - Express NodeJS

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors())

app.post('/test', function (req, res) 
{
  return res.send({ message: 'Any response' });
})

I receive my POST data from client with no issue, But i get no response from server. Almost tried everything but i get this error on response

body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: "" 

Any help appreciated.

Aqil
  • 104
  • 10
  • I'm sure that if you look in your chrome dev tool you get CORS Policy error, can you check please? – Ethanolle Feb 21 '21 at 18:41
  • 1
    Have you tried with removed `mode:"no-cors",` ? Here you can read more on this: https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors – mehowthe Feb 21 '21 at 19:07
  • Damn, @mehowthe, Man i appreciate you, Did not expect this one. You saved my day! – Aqil Feb 21 '21 at 19:15

1 Answers1

0

Thanks to @mehowthe, This issue was fixed by removing mode:"no-cors"

Aqil
  • 104
  • 10