Can't parse JSON from POST request using express in react - javascript

I'm having a problem parsing my JSON request using express, and after many hours of trying to research it, I can't figure out what the problem is.
Here is my code snippet
app.post('/Information', (req, res)=> {
console.log(req.body); // this prints out the exact POST request from Postman
const info = JSON.parse(req.body); // this returns SyntaxError: Unexpected token o in JSON at position 1
let insertQuery = `insert into Information(id, name, number, message)
values(${info.id}, '${info.name}', '${info.number}', '${info.message}')`
client.query(insertQuery, (err, result)=>{
if(!err){
res.send('Insertion was successful')
}
else{ console.log(err.message) }
})
client.end;
})
I know the reason behind the parsing error, trying to parse an 'o', because req.body is an object, but I tried the three methods of accessing properties of an object, and I get 'undefined'. I don't know if this will help, but if I send this POST request { "id":"3", "name":"Mark Zuckerberg", "number":"1112223333", "message":"Welcome to Facebook!" } from Postman, then this is what console.log(req.body) will print out {'{\r\n "id":"3",\r\n "name":"Mark Zuckerberg",\r\n "number":"1112223333",\r\n "message":"Welcome to Facebook!"\r\n}\r\n': ''}. This output looks odd to me because of the (: '') at the end, as it makes it look like there are only 2 properties for some reason and I don't understand why that's happening. I would be glad to try out any ideas you guys have, because I'm really lost right now. Thank you in advance.

Related

Sending an object, in a get request, in params, in postman

I'm new here on the site, I opened this user a few days ago.
I want to send in a get object request, I do it through the postman.
I'm trying to do it, but it's not working for me, I probably have a little problem somewhere.
This is what I'm trying to do.
In postman:
Axios get request:
app.get('/realtimeConversations', FBAuth, getRealtime);
The function I run on the server side.
exports.getRealtime= (req, res) => {
console.log(JSON.stringify("testing"));
console.log(JSON.stringify(req.query));
console.log(req.query.user);
console.log(req.query.user.uid_1);
console.log(req.query.user.uid_2);
return res.json([]);
}
i try to use JSON.parse instead but this is not working for me:\
exports.getRealtime= (req, res) => {
console.log(JSON.stringify("testing"));
console.log(JSON.stringify(req.query));
console.log(JSON.parse(req.query.user));
console.log(JSON.parse(req.query.user).uid_1);
console.log(JSON.parse(req.query.user).uid_2);
return res.json([]);
}
I can get the object, but I can't access the values inside it
These are the prints I get on firebase:
what you are using currently is :
{ uid_1: "user.handle", uid_2: "userUid" }
here the key name which is a string is not enclosed with doublie quotes so its not a valid json and hence JSON.parse will fail.
use query parameter as :
{ "uid_1": "user.handle", "uid_2": "userUid" }
you can check this is in postman side itself .
Try the below code in postman pre-request or test scrit
console.log(JSON.parse(pm.request.url.query.get("user")).uid_2)

Unexpected token O in JSON at position 0 when I query an API

I know that the question is findable on the forum but no answer works for me. I have an angular service that calls a nodeJS API like this:
Angular service
public createUser(pUser: User): Observable<User> {
var url = "http://localhost:5000/users";
var json = JSON.stringify(pUser)
return this.http.post<User>(url, pUser)
}
NodeJS API
router.post('/', (req, res) => {
console.log(req.body)
User.create({ email: req.body.email, password: req.body.password })
res.sendStatus(200);
});
The API is well called, the insertion into database works, but I have this message in the browser:
SyntaxError: Unexpected token O in JSON at position 0
The status of the request is 200 on return but the error is still present in the browser
I do not know if the problem comes from the front end or the backend.
After doing some research, I try to parse my object before sending it. I try to stringify too.
Without success
Is this someone would have the solution? thank you very much
This error occurs when you try to parse invalid JSON.
Due to the default response type for angular is JSON and the default response of code 200 is 'OK'. You have to adapt one of them.
You can change the response type to text like this:
this.http.post<User>(url, pUser, {responseType: 'text'});
Or you return a JSON object:
res.status(200).send({ status: 'OK'});
It is good practise to send status 204 (No Content) if You don't send any content in response:
res.sendStatus(204);
Your Angular App should handle it and will not throw an error.
If You send status 200, it's good to add some json object, e.g. {status: "OK"} in res.status(200).send({status: "OK"}). Otherwise You will send the string 'OK' and will get "Unexpected token O ..." (O from 'OK').
From Express doc:
res.sendStatus(200) // equivalent to res.status(200).send('OK')

Post request for an API-endpoint "Unexpected token u in JSON at position 0"

I am creating an api-endpoint (using node.js) to post data to mysql db and receiving this error in postman:
"Unexpected token u in JSON at position 0".
I've done a similar function for a GET request with an example of the json data that will be posted to my endpoint, and that works as it should and is injected in the db (no need to show the whole function with queries as the error occurs in this small snippet). When doing the post request I get the error. Any ideas what I'm doing wrong here. I'd appreciate any feedback!! Cheers!
app.post('/', (req, res) => {
function callback(error, response, body) {
let object = JSON.parse(body);
let objectItems = object._items[0]
});
console.log(objectItems)
}
callback(req);
})

Handling error using request module - undefined object

I am trying to get coordinates of locations using Mapbox API via request module in my express app. URL of the request (specific location) is given through html form. It is parsed in the url and the API provides all the information, including coordinates. It looks like this:
app.post("/", function(req, res){
var location = req.body.location;
var url = "https://api.mapbox.com/geocoding/v5/mapbox.places/" + location + ".json?access_token=MY_TOKEN"
request(url, function(error, response, body) {
var data = JSON.parse(body);
var coordinates = data.features[0].geometry.coordinates
Everything works well if I try any location that an API can find and process. But when I tried inserting some random characters through the form the app crashes, giving the error "TypeError: Cannot read property 'geometry' of undefined". Console.log(data) shows that the features element of data object is an empty array [ ].
I tried handling the error by showing message and redirecting when data is undefied, like this:
if (!data.features) {
req.flash("error", "Location not found, please try again.")
res.redirect("/")}
Im at the beginning of my coding journey and this is my first request so I highly appreciate any help, thanks!
Sorry was off on my weekend.
If data.features is an empty array it won't fail the test (!data.features).
You could try something like
if(Array.isArray(data.features) && data.features.length>0){
//code here
}else{
req.flash("error", "Location not found, please try again.")
res.redirect("/")
}

Using the PUT method with Express.js

I'm trying to implement update functionality to an Express.js app, and I'd like to use a PUT request to send the new data, but I keep getting errors using PUT. From everything I've read, it's just a matter of using app.put, but that isn't working. I've got the following in my routes file:
send = function(req, res) {
req.send(res.locals.content);
};
app.put('/api/:company', function(res,req) {
res.send('this is an update');
}, send);
When I use postman to make a PUT request, I get a "cannot PUT /api/petshop" as an error. I don't understand why I can't PUT, or what's going wrong.
You may be lacking the actual update function. You have the put path returning the result back to the client but missing the part when you tell the database to update the data.
If you're using MongoDB and ExpressJS, you could write something like this :
app.put('/api/:company', function (req, res) {
var company = req.company;
company = _.extend(company, req.body);
company.save(function(err) {
if (err) {
return res.send('/company', {
errors: err.errors,
company: company
});
} else {
res.jsonp(company);
}
})
});
This mean stack project may help you as it covers this CRUD functionality which I just used here swapping their articles for your companies. same same.
Your callback function has the arguments in the wrong order.
Change the order of callback to function(req, res).
Don't use function(res, req).
Also if you want to redirect in put or delete (to get adress), you can't use normal res.redirect('/path'), you should use res.redirect(303, '/path') instead. (source)
If not, you'll get Cannot PUT error.
Have you been checking out your headers information?
Because header should be header['content-type'] = 'application/json'; then only you will get the update object in server side (node-express), otherwise if you have content type plain 'text/htm' like that you will get empty req.body in your node app.

Categories

Resources