This question already has an answer here:
Error when accessing API with fetch while setting mode to 'no-cors' [duplicate]
(1 answer)
Closed 1 year ago.
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.
Thanks to #mehowthe, This issue was fixed by removing mode:"no-cors"
Related
I'm trying to learn about HTTP Post requests, here's my code:
Client Side:
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('/api', options).then(response =>{
console.log(response);
});
Server-Side:
const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));
app.use(express.json({limit: '1mb' }));
app.use(express.static('public'));
app.post('/api', (request, response) => {
console.log('I got a request!');
console.log(request.body);
const data = request.body;
response.json({
status: "success",
latitude: data.lat,
longitude: data.lng
});
});
It leads to the following error on my localhost console:
ERR_ABORTED 405 (Method Not Allowed)
And it is complaining about the "fetch" line on the client side code. So there is an issue with the post. Does anyone know what the problem is?
I need to receive a JSON from my front in React. But the JSON comes to me in a strange way (an object with the data in string), I don't know how to return it to type object again.
I send this.
const data = {
email: 'emailc#email.com',
password: 'test'
}
const options = {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const onsubmit = (e) => {
//evitamos que se haga la peticion en automatico
e.preventDefault();
fetch('http://localhost:3001/user/signin',options)
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
console.log('send on submit');
}
and I get this on the express server:
[Object: null prototype] {
'{"email":"emailc#email.com","password":"test"}': ''
}
My server is configured in this way:
const express = require('express');
const app = express();
const morgan = require('morgan');
const cors = require('cors');
const {mongoose} = require('./src/database/connection')
const Parser = require("body-parser").urlencoded({ extended: false });
//config
app.set('port', process.env.PORT || 3001);
//middlewares
app.use(morgan('dev'));
app.use(Parser);
app.use(cors()); //accepts connection from all directions
//Routes
app.use(require('./src/test'));
app.use(require('./src/routes/users'));
//Server
app.listen(app.get('port'), (req, res) => {
console.log(`Server on port ${app.get('port')}`);
})
I think I have misconfigured the body-parser, please help, it is my first API.
'Content-Type': 'application/x-www-form-urlencoded'
If you tell the server you are sending Form Encoded data then it is going to try to parse what you send as Form Encoded data.
Don't lie.
If you are sending JSON, say so:
'Content-Type': 'application/json'
const Parser = require("body-parser").urlencoded({ extended: false });
You also need a body parser that supports JSON.
const Parser = require("body-parser").json();
But Express has a built-in body parser and variable names starting with capital letters are traditionally reserved for constructor functions / classes.
const parser = express.json();
Aside:
mode: 'no-cors'
If you are making a cross-origin request then that will break it.
If you are making a same-origin request then that will do nothing.
Remove it.
fetch(REST+'/signup', {
mode: 'cors',
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ id: id, pw: pw })
}).then(async (res) => {
let json = await res.json();
if (json.result === true) {
this.setState({ view: 'login' });
}
});
this is my client's POST request part.
my react app uses port 3000
and my REST server is using 80
I already declared using cors in my REST server like this
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors()); // enable CORS to prevent same origin policy error
and this is rest of my REST server code
app.post('/signup', (req, res) => {
console.log(req.body);
...
res.send(JSON.stringify({
result: true
}));
});
when I used cURL to test REST server, it says
$ curl --header "Content-Type: application/json" --request POST --data '{"id": "gksrlf2ek", "pw": "hangil2da!"}' http://localhost/signup
{"result":true}
but using my react app, REST server gets {}. empty object.
I made a node server with the three packages express, body-parser and cors.
I am trying to access data from client-side in my app.js with an async/await function that has a post request with the required data that I want to fetch
here's the fetch request and the post request in app.js, I am trying to pass the data [temperature, date, userResponse] via the postData function in app.js:
//post routes
const postData=async function postData(url = 'http://api.openweathermap.org/data/2.5/weather?zip=', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return await response.json();
}
postData('/add', {temperature: '1', date: '2', userResponse: '2'});
}
and here's the server side code where I made an add route as post route:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
const port = 3000;
// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);
function sendData (request, response) {
response.send(projectData);
};
// TODO-ROUTES!
const data=[]
app.post('/add', function(req,res){
data.push(req.body)
console.log(data)
})
here's what I got when I ran the project on localhost:3000
I want the the parameters temperature, date and userResponse to appear in the console
the errors at line 35 related to the post request are :
app.js:35 POST http://localhost:3000/add net::ERR_EMPTY_RESPONSE
app.js:48 Uncaught (in promise) TypeError: Failed to fetch
never mind the errors at the two above lines related to the get request
in vs code I can see this(the temperature, date and userResponse appear in the terminal but don't appear in the localhost:3000 console in the browser):
I just need the client-side to pass data to server-side dynamically and not just pass the response in the server-side
You are not sending any response back from the server. Send some response as below
app.post('/add', function(req,res){
data.push(req.body)
console.log(data)
return res.send({}); //return whatever response you need to send
})
I have already searched a lot, but none of the solutions found work: Cannot send content-type by axios. but if I use the postman interceptor and I 'send' the request generated by axios this time it works: the node.js / express server correctly receives the request and body-parser works normally!
React side:
const API_URL = "http://localhost:8800/auth/";
const headers = {
accept: 'application/json, text/plain, */*',
'content-type': 'application/json;charset=UTF-8'
};
class AuthService {
register(pseudo, email, password) {
return axios.post(API_URL + "signup/",
{ pseudo, email, password },
{ headers: headers})
.then(response => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
});
}
server side
const app = express();
app.use(function (req, res, next) {
console.log( req.headers);
next();
});
app.use( bodyParser.urlencoded({ extended: true }), bodyParser.json());
Usually when I use axios I send the headers in a config variable like this and I stringify the body so it sends as JSON object and not a JS object.
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const body = JSON.stringify({arguments});
try {
const res = await axios.post(/url, body, config);
...
Here's a link to the docs for a little more reading about it:
https://github.com/axios/axios