How to fix javascript not sending any req.body to server - javascript

I m not getting any req.body parameters. Its working perfectly fine while posting with postman
Code:
async function postRequest(url, data){
const response = await axios.post(url, data, {
headers: {
"Content-Type": "application/json"
}
})
return response.data
}
server side:
app.use(bodyParser.urlencoded({extended: true}))
I use this before adding any app.get functions.
Any help would be appreciated.
FYI I use reactjs

You set the content type to json but your server is expecting application/x-www-form-urlencoded. You should set the content type to application/x-www-form-urlencoded
async function postRequest(url, data){
const response = await axios.post(url, data, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
return response.data
}

Try to use
'''
app.use(bodyParser.json())
'''

Related

When I post data with fetch post, I don't receive data

I have a problem with fetch post, I want to send data to an url but it doesn't work..
function TodoTaskForm () {
const taskContentInput = useRef(null)
const handleSubmit = async (e) => {
e.preventDefault()
fetch('/api/tasks', {
method: 'POST',
body: JSON.stringify({content: taskContentInput.current.value})
})
}
return (
<form onSubmit={handleSubmit} className="__component_todolist_form_container">
<input type="text" name="task" ref={taskContentInput} placeholder="nouvelle tâche.."></input>
</form>
)
}
In my component, I'm doing this and in my express server :
app.post('/api/tasks', (req, res) => {
console.log(req.body)
console.log('request received!')
})
When I test, i receive the request but req.body return "{}" in my console, I don't understand, im using app.use(express.json()) but it doesn't work, I have even try to use body-parser but...
So please, I need help.. thank you!
You need:
A body parser which matches the data being send. You've switched from sending form encoded data to sending JSON. Note that Express has built-in body parsing middleware and does not need the separate body-parse NPM module.
A Content-Type header on the request which states what format the data is in so the correct body parser can be triggered.
Such:
app.post('/api/tasks', express.json(), (req, res) => {
console.log(req.body)
console.log('request received!')
})
and
fetch('/api/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({content: taskContentInput.current.value})
})

Send data from JavaScript to node.js

Below is the JavaScript code. How can I send the players array to node.js?
let players = [];
for(var i=0; i<22; i++){
players.push($(".card > button").eq(i).attr("value"));
}
Below is the node.js code.
const express = require("express");
const bodyParser = require("body-parser");
const mySql = require("mySql");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.get("/play", function(req, res){
res.render("PlayGame");
});
app.post("/play", function(req, res){
res.render("PlayGame");
});
I need to catch the players array at /play route in node.js. How can I do that?
Yes, you can send data from the browser Javascript to your node.js app. You would use an Ajax call and use either the XMLHttpRequest API or the more modern fetch() API to send the data. You would create a route in your nodejs server such as /play and then send the data with the request. Your server will then need to parse the incoming data (depending upon how it was sent) and can then act on it.
You will also have to decide if you're sending a GET, POST or PUT request (picking what is appropriate based on typical REST design and architecture). If this is starting a game and you're sending a bunch of data with it, then you would probably use a POST request and send the data as JSON in the body of the request.
In Express, here's how you'd receive that type of data:
app.use(express.json());
app.post("/play", (req, res) => {
console.log(req.body); // this would be the data sent with the request
res.send("game started");
});
In the browser, here's how you could send an array of players to your server.
fetch("/play", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(players)
}).then(response => {
// this line of code depends upon what type of response you're expecting
return response.text();
}).then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
See the "Using Fetch" page on MDN for more info.
On the client side you would need something like this:
const postData = data => {
const body = JSON.stringify(data);
return fetch('https://your.url/play', {
method: 'POST', // GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, same-origin
cache: 'no-cache', // default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, omit
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow', // manual, follow, error
referrer: 'no-referrer', // no-referrer, client
body
})
.then(response => response.json()) // parses JSON response into native JavaScript objects
}
const players = ['a', 'b', 'c'];
postData({data: players})
.then(json => {
console.log(json);
})
.catch(e => console.log(e));
On the server side you would need something like this:
app.use(express.json());
app.post("/play", (req, res) => {
const players = req.body.data;
...
...
});

JSON is becoming empty upon hitting server code

I am sending a fetch request with a JSON payload from my webpage like this:
let raw = JSON.stringify({"name":"James","favourite":"books"})
var requestOptions = {
method: 'POST',
body: raw
};
let send = () => {
fetch("http://mywebsite.herokuapp.com/send", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
On the server side I am getting an empty body {}. Here is the code I use to monitor that:
app.post('/send', (req, res) => {
console.log(req.body)
})
When I send the exact same code generated with Postman to server — somehow everything works fine, and I get the correct JSON. Please help me understand why that is.
On the server, req.body will be empty until you have middleware that matches the content type in the POST and can then read the body from the response stream and populate req.body with the results.
// middleware to read and parse JSON bodies
app.use(express.json());
app.post('/send', (req, res) => {
console.log(req.body);
res.send("ok");
});
And, then on the client side, you have to set the matching content-type, so the server-side middleware can match the content-type and read and parse it:
const requestOptions = {
method: 'POST',
body: raw,
headers: {
'Content-Type': 'application/json'
},
};

HTTP Post request not sending body or param data from ionic

HTTP post request is not sending body or param data to the server
Forgive me if this turns out to be a duplicate question. I've looked at several similar questions on stack overflow, but none of them have solved my problem. Also tried using a GET request instead of a POST request, but body data is still not sending.
Client side code:
// ionic code
homeUrl: string = 'http://localhost:80';
let obj = {"name": "Guest"};
let response = this.httpClient.post(this.homeUrl + '/admin-signup', JSON.stringify(obj));
response.subscribe(data => {
console.log('response: ', data);
//TODO: handle HTTP errors
});
Server side code:
server.post('/admin-signup', (req, res) => {
console.log('sign')
console.log(req.body);
// TODO: Process request
res
.status(200)
.send(JSON.parse('{"message": "Hello, signup!"}'))
.end();
});
First of all, import http client
import { HttpClient, HttpHeaders } from '#angular/common/http';
Then do the following
const header = new HttpHeaders({
'Content-Type': 'application/json',
Accept: 'application/json'
//api token (if need)
});
const options = {
headers: header
}
let response = this.httpClient.post(this.homeUrl + '/admin-signup', obj, options);
response.toPromise().then(data => {
console.log('response: ', data);
//TODO: handle HTTP errors
}).catch((err) =>{
console.log('error', err);
});
Hope it solve your problem.
I'm not familiar with ionic
but I'm guessing its a cors issue
can you try use cors?
const cors = require('cors');
app.use(cors());

Getting invalid JSON on API call

I'm trying to use GoToMeeting's API and making a POST request to create a meeting. At the moment, I'm just trying to hardcode the body of the meeting and send headers but I'm receiving and I'm invalid JSON error and not sure why. Here's the code for that route:
app.post('/new-meeting', (req, res) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application / json',
Authorization: 'OAuth oauth_token=' + originalToken
};
console.log('-----------------------------------------------------------')
console.log('Acess Token:');
console.log('OAuth oauth_token=' + originalToken);
console.log('-----------------------------------------------------------')
const meetingBody = {
subject: 'string',
starttime: '2018-03-20T08:15:30-05:00',
endtime: '2018-03-20T09:15:30-05:00',
passwordrequired: true,
conferencecallinfo: 'string',
timezonekey: 'string',
meetingtype: 'immediate'
};
return fetch('https://api.getgo.com/G2M/rest/meetings', {
method: 'POST',
body: meetingBody,
headers: headers
}).then(response => {
console.log('response:');
console.log(response);
response
.json()
.then(json => {
res.send(json);
console.log(req.headers);
})
.catch(err => {
console.log(err);
});
});
});
When I hit that router, I get the following error:
{
"error": {
"resource": "/rest/meetings",
"message": "invalid json"
}
}
Any advice would be appreciated!
tl;dr
You are passing fetch a value for the body represented by a JavaScript object. It is converting it to a string by (implicitly) calling its .toString() method. This doesn't give you JSON. The API you are calling then complains and tells you that it isn't JSON.
You need to convert your object to JSON using:
body: JSON.stringify(meetingBody),
Test case
This demonstrates the problem and the solution.
Server
This is designed to be a very primitive and incomplete mock of GoToMeeting's API. It just echos back the request body.
const express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.text({ type: "*/*" }));
app.post("/", (req, res) => {
console.log(req.body);
res.send(req.body)
});
app.listen(7070, () => console.log('Example app listening on port 7070!'))
Client
This represents your code, but with the Express server stripped out. Only the code relevant for sending the request to GoToMeeting's API is preserved.
const url = "http://localhost:7070/";
const fetch = require("node-fetch");
const headers = {
'Content-Type': 'application/json',
Accept: 'application / json',
Authorization: 'OAuth oauth_token=foobarbaz'
};
const meetingBody = {
subject: 'string',
starttime: '2018-03-20T08:15:30-05:00',
endtime: '2018-03-20T09:15:30-05:00',
passwordrequired: true,
conferencecallinfo: 'string',
timezonekey: 'string',
meetingtype: 'immediate'
};
fetch(url, {
method: 'POST',
body: meetingBody,
headers: headers
})
.then(res => res.text())
.then(body => console.log(body));
Results of running the test case
The logs of both server and client show:
[object Object]
This is what you get when you call meetingBody.toString().
If you change the code as described at the top of this answer, you get:
{"subject":"string","starttime":"2018-03-20T08:15:30-05:00","endtime":"2018-03-20T09:15:30-05:00","passwordrequired":true,"conferencecallinfo":"string","timezonekey":"string","meetingtype":"immediate"}
This is JSON, which is what the API is expecting.
Aside
MIME types do not have spaces in them. Accept: 'application / json', should be Accept: 'application/json',. This probably isn't causing you any problems though.
I believe the header is incorrect.
You need 'Accept: application/json' without space.

Categories