I am running a node.js server running express.js on my local machine and need to decode a request made by the client, that contains a json string in it. I run the code below and get the following error.
SyntaxError: Unexpected token v in JSON at position 2
at JSON.parse (<anonymous>)
at C:\myLocation\source\repos\server\server\server.js:144:19
at Layer.handle [as handle_request] (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\myLocation\source\repos\server\server\node_modules\express\lib\router\index.js:317:13)
My request is
http://localhost:1337/%7B%22Code%22:%22VNdVwY9iWhFZ114CjcDZbY%22,%22Chat%22:%22Test.txt%22%7D
The expected json is
{"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
I get the json, but it still gives me the same error.
My code:
app.use(function (req, res) {
//console.log(req.url)
var myStr = req.url.replace('/', '')
if (myStr != false) {
let decodeStr = decodeURIComponent(myStr)
var test = JSON.parse(decodeStr)
var json = JSON.stringify(test)
if (json.includes(createkey)) {
console.log("Create: " + json)
createFile(req, res, test)
} else if (json.includes(modKey)) {
console.log("Modify: " + json)
modifyFile(req, res, test)
} else if (json.includes(readFileKey)) {
console.log("Read: " + json)
readFile(req, res, test)
}
} else {
res.sendStatus(404)
console.log("home")
}
})
Why do I get the error?
Edit 1
I added console.log(decodeStr)but I still get the error. It returns {"Code":"VNdVwY9iWhFZ114CjcDZbY","Chat":"Test.txt"}
{"Code":"'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"} is not a valid json, that's why you encounter that error,
The other way around, you could parse
JSON.parse('{"Code":"\'GAHGAaphgAP:gjpaGHAHAG{AaGRAP;GHPG;RA","Chat":"Test.txt"}')
Try
var uri = "http://localhost:1337/%7B%22Code%22:%22%5C'GAHGAaphgAP:gjpaGHAHAG%7BAaGRAP;GHPG;RA%22,%22Chat%22:%22Test.txt%22%7D";
Related
I have made a small vanilla javascript code to fetch api but it is throwing the error "Uncaught (in promise) SyntaxError: Unexpected token N in JSON at position 0". I m not able to understand, exactly why the error is caught. Can somebody help me to resolve this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
.then(function(response) {
return response.json();
})
.then(function(apiResponse) {
// Output API response to console to view.
console.log(apiResponse);
});
It's because of this.
const config = {
url: "https://randomuser.me/",
numberCards: 24
};
fetch(`${config.url}&amount=${config.numberCards}`)
It should be,
const config = {
url: "https://randomuser.me/api/",
numberCards: 24
};
fetch(`${config.url}?amount=${config.numberCards}`)
It's because the json data are from "https://randomuser.me/api/". Not "https://randomuser.me/". And the query strings must begin with a "?" mark. "&" mark is used to separate query strings. (like this "https://example.com/?amount=24&hi=en")
On the response of an HTTP GET call (with native http module), I try toJSON.parse() the response after the end event is emitted. I know for sure the the data i'm getting is valid JSON but still the JSON.parse throw an error. And my logs indicate that the JSON.parse is invoked before it should.
res.on("end", () => {
console.log('Req ended message is', body);
try {
var passport = JSON.parse(body);
} catch (e) {
w.info(
"Cannot parse the response from : " +
process.env.mongo_api_host +
" | error : " +
e
);
}
callback(passport);
return;
});
And my log shows :
info: Getting MongoDB passport for model : CESI
info: Cannot parse the response from : mongo_api | error : SyntaxError: Unexpected end of JSON input
info: Req ended message is *long valid JSON data*
We can clearly see in the logs that the parse error is caught and logged before the "Req ended message is : ... stuff".
What am I missing ?
Edit 1 :
Even by putting callback(passport) inside try block as suggested in comment it still does it :
res.on("end", () => {
try {
console.log("Req ended message is", body);
var passport = JSON.parse(body);
//TODO What if you get an array ?
if (passport._id) delete passport._id;
callback(passport);
} catch (e) {
w.info(
"Cannot parse the response from : " +
process.env.mongo_api_host +
" | error : " +
e
);
}
return;
});
I wrote a smart contract for creating simple database. It contains multiple functions , when i hit an REST api first time it gives me correct output but at further hits it make node server crash with a message --
F:\project\blockchain\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module
.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=type
of process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(EN
VIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write
(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath"normalize";var ret=nodeFS["readFileSync"](file
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at ServerResponse.header (F:\project\blockchain\node_modules\express\lib\response.js:725:10)
at ServerResponse.send (F:\project\blockchain\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (F:\project\blockchain\node_modules\express\lib\response.js:256:15)
at F:\project\blockchain\BlockchainDB\users\userFunction.js:37:47
at F:\project\blockchain\node_modules\web3\lib\web3\filter.js:120:21
at Array.forEach (native)
at F:\project\blockchain\node_modules\web3\lib\web3\filter.js:119:32
at Array.forEach (native)
at Object.onMessage [as callback] (F:\project\blockchain\node_modules\web3\lib\web3\filter.js:117:22)
my code for api
module.exports.creation=function(req,res){
var user_id = req.params.user_id || req.body.user_id;
var currency = req.params.user_id || req.body.currency ;
if(user_id == undefined || currency == undefined){
res.status(500).json({status:false,errors:"Empty parameters"});
}else{
isaccount().then(function(accountNumber){
if(accountNumber!=null){
var timestamp = Date.now();
var result = contract.createUser.sendTransaction(user_id,currency,accountNumber,timestamp,{from:web3.eth.coinbase,gas:600000});
var event = contract.CreatedUser(function(error, result) {
if (!error){
if(result.args.userId!= undefined && result.args.accountId!= undefined && result.args.categoryId!= undefined){
logger.info("user created with id :"+result);
res.status(200).json({status:true,data:{iduser:result.args.userId,accountId:result.args.accountId,created_at:timestamp}});
}else{
logger.info("user creation have problem :");
res.status(500).json({status:false,errors:"no response"});
}
}else{
logger.error(error);
res.status(500).send(false);
}
});
}else{
logger.debug("Problem in accountNumber generation");
res.status(500).send(false);
}
});
}
}
please help me to solve this problem
Thanks in advance
Try using return statement for all the res.status() calls. So, even though once the response status gets set to something, it is again getting res.status() somewhere after it.
I am at a dead end. I am baffled. I am passing a stringified dictionary from Python (using json.dumps()) through UDP to an Ionic 2 (Typescript) application.
The python code generating the messages:
message = { 'time' : str(round(float(op('indexFraction')[0]),3)) }
messageJSON = json.dumps(message)
#messageJSON = json.JSONEncoder().encode(message)
print(messageJSON)
op('udpout').send(messageJSON) #sending out of TouchDesigner
My callback function on the Ionic side looks like this:
socket.on('message', function (message, remoteAddress) {
if (message.length > 0) {
console.log(message, typeof(message));
// alert(message);
// process response message
var data = JSON.parse(message);
console.log(data);
if (data.time) {
alert(data.time);
}
}
});
A sample message looks like this (typeof string):
{"time": "0.934"}
// this is a string, as evidenced by the Console.log
JSON.parse() throws the following:
index.html:1 Uncaught SyntaxError: Unexpected token in JSON at position 17
I've tried all kinds of variants on the object. It passes as valid on JSONlint. It's so simple, no wacky characters. Any ideas?
Thanks,
Marc
I am receiving the error:
undefined:1
'{"completed_in":0.078,"max_id":333655176038719488,"max_id_str":"3336551760387
^
SyntaxError: Unexpected token '
at Object.parse (native)
at /home/tweets/10seconds.js:25:25
at passBackControl (/home/tweets/node_modules/oauth/lib/oauth.js:367:11)
at IncomingMessage.<anonymous> (/home/tweets/node_modules/oauth/lib/oauth.js:386:9)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:895:16
at process._tickCallback (node.js:415:13)
When parsing Twitter API JSON from the Search API.
The code I am using the parse this JSON is:
MongoClient.connect("mongodb://localhost:27017/db", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection("tweets");
while(run < 200){
oa.get("http://search.twitter.com/search.json?q=morning&rpp=100&include_entities=true&result_type=mixed", access_token, access_token_secret, function(error, data) {
var theTweets = JSON.parse(sys.inspect(data));
collection.insert(theTweets, {w:1}, function(err, result) {});
console.log(run);
});
run = run + 1;
}
});
What could cause this?
Probably, the output of sys.inspect is not JSON it adds the quote '.
Why are you using sys.inspect?
If data is a JSON string, then use JSON.parse(data); and if it's an object already, well you don't have to use JSON.parse at all...
The problem is on the sys.inspect() call as already stated by the other answers and comments.
As stated in the nodejs documentation (http://nodejs.org/api/util.html#util_util_inspect_object_options):
Return a string representation of object, which is useful for debugging.
By the way, it seems they changed the sys module name to util.
You can easily make a small test by running the following code on an older node version. It should throw your error:
var sys = require('sys');
var data = '{"test":1, "test2":2}';
sys.puts(JSON.parse(sys.inspect(data)));
And then remove the sys.inspect call. It should correctly parse the object:
var sys = require('sys');
var data = '{"test":1, "test2":2}';
sys.puts(JSON.parse(data));