Error: SyntaxError: Unexpected token o in JSON at position 1
Code:
collection3.find({username: req.body.accept}).toArray((error, user) => {
a = JSON.parse(user)
})
This is happening because the user variable is an object. The JSON.parse function expects to be passed a string, not an object. If you pass an object, you will get the 'Unexpected token o' error message. You can produce this error message directly by running the following code:
JSON.parse({})
The working equivalent of the above code is:
JSON.parse('{}')
Related
Me and others are experiencing this error: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following this tutorial on JSON Web Tokens (LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s, around minute: 10:00)
The error appears during this POST request:
Content-Type: application/json
{
"username": "Kyle",
}
You can find the full code up to that point here:
https://github.com/emanuelefavero/json-web-tokens
There are 3 main files to watch for:
server.js
.env (I left the .env file in the github repository)
request.rest (I used this file to make POST request but you can use POSTMAN or other methods)
The error seems to be in server.js, specifically in the express-JWT method:
app.post('/login', (req, res) => {
// Authenticate User
// Create json web token
const username = req.body.username
const user = { name: username }
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
console.log(accessToken)
res.json({ accessToken: accessToken })
})
The GET request is working fine.
While I'm trying to fix this error I'll still respond to any questions and provide project details if needed. Thank you.
Full Error Message:
SyntaxError: Unexpected token } in JSON at position 24
at JSON.parse (<anonymous>)
at parse (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/types/json.js:89:19)
at /Users/arch0n/Desktop/JWT/json-web-token/node_modules/body-parser/lib/read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:199:9)
at invokeCallback (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:231:16)
at done (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:220:7)
at IncomingMessage.onEnd (/Users/arch0n/Desktop/JWT/json-web-token/node_modules/raw-body/index.js:280:7)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
It appears the issue lies in the request you're making. You have a trailing comma in the JSON that you are sending in your request.
If you are new to using JSON & JavaScript, just try to remember that JavaScript objects !== JSON.
In JS Objects, you can have trailing commas. However, in JSON it will cause issues.
Prevent server from crashing.
I am testing an API with Postman where I am expecting a number with or without decimal places.
But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.
Postman:
{
"concept": "Text",
"incomeAmount": 1)0000,
"expenseAmount": 89,
"description":"Text"
}
Failed response:
SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I am using express validator like this:
router.post('/new-income',
[
check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),
],
validation,
newItem
);
And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.
const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');
if (!regAmount.test(incomeAmount)) {
return res.json ( {
'msg': 'Only positive numbers without signs are allowed'
} );
}
Thanks for your help!
With this much information I can only assume that you are using some kind of json middleware that parse the incoming data.
Unfortunately, the data you sent via postman is not in a valid json format. Ironically enough, only valid number are accepted as value without the need of quotation mark (excluding array and object).
A solution maybe to send the data as pure text to your api and then run in through your validation before converting it into a number.
You can verify the json format yourself here: https://jsonformatter.curiousconcept.com/
This is expected. You're sending illegal JSON so your JSON parsing middleware gets an exception. To catch/handle this error, you need to either install custom middleware that catches the error in the middleware or catch the error from the existing JSON parser in the Express error handler by installing your own Express error handler.
Also, if you're using the express.json() middleware, it has a verify callback option that you can pre-check the JSON if you want, but frankly, it's probably easier to just have an Express error handler and get the error there.
I am getting an error that says SyntaxError: Unexpected token a in JSON at position 0
and I cannot find any information on what "a" means. I know that the JSON is not undefined.
Can anyone help me understand what is causing this error?
Here is the code block that is causing the error:
let db_creds = await getDBCredentials();
console.log(db_creds)
const pool = new Pool(JSON.parse(db_creds['SecretString']));
console.log(pool)
Unexpected Token < in JSON at Position 0. From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. ... json() method on the fetch object, it can result in a JavaScript exception being thrown.
What Is JSON and How to Handle an “Unexpected Token” Error
Well for me it was because the port was already in use and it must be sending HTML, you can try killing the port by running the below command in cmd(admin mode)
taskkill /F /IM node.exe
I am trying to log my errors and send notification to a channel. When I use console.log() I get a description of the error message but when I use JSON.strigify it returns an empty object. How can I fix this issue please.
When I run this code:
console.log(err);
console.log("stringify", JSON.stringify(err));
I get this response:
ReferenceError: School is not defined
at /Users/macbookpro/Documents...
at Layer.handle [as handle_request] (/Users/macbookpro/Documents...
at next (/Users/macbookpro/Documents...
at adminAccess (/Users/macbookpro/Documents...
at processTicksAndRejections (node:internal/process/task_queues:96:5)
strinfify {}
I need the error message, and for me to send it successfully using axios, I need to JSON.stringify() the error message.
Most properties on an error object are non-enumerable, so you need to do something like this:
let error = new Error('nested error message');
console.log(JSON.stringify(error))
console.log(JSON.stringify(Object.assign({},
error,
{ // Explicitly pull Error's non-enumerable properties
name: error.name,
message: error.message,
stack: error.stack
}
)))
if have the following code:
socket.on('getNeighbors', function(data)){
if( typeof data !== undefined ){
do something...
}
});
But when I try to send this packet without data my server crashes with the TypeError: Cannot read property '...' of undefined (in this case data).
I understand the reason behind the error, but how can I prevent my server from crashing? How can I catch the error before I get inside of the if-clause? I thought I can manage this by checking if data is undefined, but that is not working :|
Greetings