Unexpected token # in JSON at position 0 - javascript

I have created an endpoint and when i am sending a request on the endpoint i am receiving the object for the offices but when it comes to the recipient i got an error of SyntaxError: Unexpected token # in JSON at position 0 and when i checked on the project's log from where i am getting the request it gives me an error of StatusCodeError: 400.but when i am sending the request using postman it doesn't give any error it worked fine. here is the code of the endpoint.
const { growthfilemsdb } = require('../config');
const { code } = require('../utils/reportUtils');
const { getBearerToken, tokenValidator } = require('../utils/http');
const update = async (req, res) => {
try {
const bearerToken = getBearerToken({ headers: req.headers })
if (tokenValidator(bearerToken)) {
const officeID = req.body.officeId;
const recipientID = req.body.recipientId;
const data = {
requestBody: req.body,
};
if (
req.body.hasOwnProperty('officeId') &&
req.body.template === 'office'
) {
const officeDb = await growthfilemsdb
.collection('Offices')
.doc(officeID)
.set(data.requestBody, { merge: false });
return res.status(code.ok).send({ success: true, message: `Success` });
} else if (
req.body.hasOwnProperty('recipientId') &&
req.body.hasOwnProperty('officeId') &&
req.body.template === 'recipient'
) {
const recipientData = await growthfilemsdb
.collection('Offices')
.doc(officeID)
.collection('Recipients')
.doc(recipientID)
.set(data.requestBody, { merge: false });
return res.status(code.ok).send({ success: true, message: `Success` });
}
} else {
res.status(code.forbidden).send('Forbidden');
}
} catch (error) {
res
.status(code.internalServerError)
.send({ success: false, message: `Internal Server Error` });
}
};
module.exports = { update };
and i have used this code in the index.js file as in this way
const bodyParser = require('body-parser');
const app = express();
const updateRecord = require('./api/updateApi');
require('dotenv').config();
app
.use(bodyParser.urlencoded({ extended: true }))
app.put('/activity', updateRecord.update);
this is the error i got when i am sending request
StatusCodeError: 400 - "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Bad Request</pre>\n</body>\n</html>\n"
at new StatusCodeError (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/srv/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/srv/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/srv/node_modules/request/request.js:1083:12)
and this is the error i am getting when i am receiving
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/worker/node_modules/body-parser/lib/types/json.js:157:10)
at parse (/worker/node_modules/body-parser/lib/types/json.js:83:15)
at /worker/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/worker/node_modules/raw-body/index.js:224:16)
at done (/worker/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/worker/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)

Related

Fetch Error while getting data from food-data-central API

So I am trying to get some data from the food-data-central API. In my program I console log the data, but I don't get any results on the console.
The only thing I get is an error about Fetch Error
import fetch from "node-fetch"
const params = {
api_key: <apiKey>,
query: 'chicken breast raw',
dataType: ["Survey (FNDDS)"],
pagesize: 5,
}
const api_url = `https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${encodeURIComponent(params.api_key)}&query=${encodeURIComponent(params.query)}&dataType=${encodeURIComponent(params.dataType)}&pageSize=${encodeURIComponent(params.pagesize)}`
function getData(){
return fetch(api_url).then(response => response.json())
}
getData().then(data => {
const foods = data.foods[0];
console.log("Protein: ");
console.log(foods.foodNutrients[0].value);
console.log("Fats: ");
console.log(foods.foodNutrients[1].value);
console.log("Carbs: ");
console.log(foods.foodNutrients[2].value);
});
The output that I get:
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
^
FetchError: request to https://api.nal.usda.gov/fdc/v1/foods/search?api_key=3Bi6rNu3MiTYMaPwMf2u5vs1xAtdKS0n5HoFpgy9&query=chicken%20breast%20raw&dataType=Survey%20(FNDDS)&pageSize=5 failed, reason: connect ETIMEDOUT 2600:1f12:18a:7d00:217:68d:2c2:3718:443
at ClientRequest.<anonymous> (/home/dflorian251/Desktop/node_modules/node-fetch/lib/index.js:1505:11)
at ClientRequest.emit (node:events:513:28)
at TLSSocket.socketErrorListener (node:_http_client:481:9)
at TLSSocket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT'
Is something wrong with the node-fetch module ?

Got "SyntaxError: Unexpected token e in JSON at position 0" message when use supertest to get token

I use supertest to test web API, and I created a function to get the token,
module.exports.getToken = () => {
let query =
{
"email": config.dev.adminUsername,
"password": config.dev.adminPassword,
"applicationId": config.dev.applicationId
}
request(config.dev.loginUrl)
.post('/login')
.send(query)
.expect(200)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
but I got error looks like,
{ SyntaxError: Unexpected token e in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.res.on (C:\WorkSpace\Postman\saasify-integration-tests\supertest_testScripts\node_modules\superagent\lib\node\parsers\json.js:11:35)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
rawResponse: 'eyJraWQiOiJ4eGh5cXV3.................FRfeCpAm3sYxY7fV-WDK1w',
statusCode: 200,
response: undefined }
But same request and url in postman I can get the token string without error. what I did wrong?

I cannot post using request-promise

My problem i that I get an error telling me I can't make post request. I use the insertDocuments function to insert messages into a database. I am attempting to make a promise oriented version of the 'mongolab-data-api' node.js module. I apologize if my question is confusing
//This is a function in a class that handles all mlab related things
var rp = require('request-promise')
var insertDocuments = options => {
if (!options.database || !options.collectionName || !options.documents) throw new Error('Database name, Collection Name, and Document(s) are required')
var opt = {
uri: `https://api.mongolab.com/api/1/databases/${options.database}/collections`,
qs: {
apiKey: this.apiKey
},
method: 'POST',
body: {
documents: options.documents
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
return rp(opt)
}
var options = {
database: 'lexybase',
collectionName: 'evy-history',
documents: msg
}
insertDocuments(options)
I get this error:
Unhandled rejection StatusCodeError: 405 - {"message":"POST not allowed."}
at new StatusCodeError (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request-promise-core/1.1.1/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/rbd/pnpm-volume/b50cbf1c-9de1-48a8-8200-48301efdd80c/node_modules/.registry.npmjs.org/request/2.88.0/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
Edit: As it turns out, the problem was that collectionName need3d to be specified and it shoul have been
body: options.documents
instead of
body: {
documents:options.documents
}
You are missing the collection name in uri:
uri: https://api.mongolab.com/api/1/databases/${options.database}/collections
should be:
uri: https://api.mongolab.com/api/1/databases/${options.database}/collections/{collectionName}
just change the collectionName
405 is returned from mongolab API

Error while calling api using node.js

I am Calling an API with with following with Node.js code but the code is always throwing an error.
Basically I am creating a bot with Microsoft Bot Framework and throwing an image to the API and evalutaing the response
var restify = require('restify');
var builder = require('botbuilder');
var http = require("http");
var request= require("request");
var rest = require('rest');
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () { });
// Create the chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
appId: 'APP_ID',
appPassword: 'APP_PASS'
});
// Listen for messages from users
server.post('/api/messages', connector.listen());
server.get('/', restify.plugins.serveStatic({
directory: __dirname,
default: '/index.html'
}));
var bot = new builder.UniversalBot(connector, function (session, results) {
var attachment = session.message.attachments[0];
request({url: attachment.contentUrl, encoding: null}, function (error, response, body) {
// Take the image and post to the custom vision service
rest.post('URL_OF_API' , {
multipart: true,
headers: {
'Prediction-Key': 'KEY',
'Content-Type': 'multipart/form-data'
},
data: {
'filename': rest.data('TEST.png', 'image/png', body)
}
}).on('complete', function(data) {
let men = 0.0; //not-men
let women = 0.0; //not-women
let topHit = { Probability: 0.0, Tag: '' };
for (var i = 0; i < data.Predictions.length; i++) {
if (data.Predictions[i].Tag === 'Men')
men = data.Predictions[i].Probability;
else if (data.Predictions[i].Tag === 'Women')
women = data.Predictions[i].Probability;
else {
if (data.Predictions[i].Probability > topHit.Probability)
topHit = data.Predictions[i];
}
}
let gender = 'No idea';
if (men > women)
gender = 'Men';
if (women > men)
gender = 'Women';
var opt='The Pic sent appears to be a'+gender+'or'+gender+'s cloth';
session.endDialog(opt);
}).on('error', function(err, response) {
session.send('Error calling custom vision endpoint');
}).on('fail', function(data, response) {
session.send('Failure calling custom vision endpoint');
});
});
});
I am getting this error
'filename': rest.data('TEST.png', 'image/png', body)
^
TypeError: rest.data is not a function
at Request._callback (C:\Users\Tushar\botforarticle\app.js:39:26)
at Request.self.callback (C:\Users\Tushar\botforarticle\node_modules\request\request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\Tushar\botforarticle\node_modules\request\request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (C:\Users\Tushar\botforarticle\node_modules\request\request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)
That's because, well, rest.data is indeed not a function.
See the docs:
https://github.com/cujojs/rest
It's not very clear what are you trying to do here, why are you doing it that way and what have you tried to fix the issue. With more context it would be easier to give you a more specific answer but without enough information all I can tell you is to read the documentation of the module that you're using or to use some other module that may better suit your needs, like request, restler, unirest, superagent or some other HTTP/REST client available in Node.

NodeJS & Typescript - Unexpected end of JSON input

I am using Node.js and Typescript to get the data from rest api. I am alway getting an error unexpected end of JSON input. Whats wrong with my code?
I have stringify my code and with http requester it is working.
My json input looks like:
{"json-input":{"handler":"getContent","image":true,"video":false,"text":false,"source":"1","lage":"testlage1"}}
My code
api.post("/getData", (req: Request, res: any, next: NextFunction) => {
let getDataUrl = "restapiexample/?async";
console.log(getDataUrl)
let filter_data:any ={}
delete req.body['keyId'];
filter_data['json-input'] = req.body;
let jsstringData = JSON.stringify(filter_data);
console.log('###################################')
console.log(jsstringData)
console.log('###################################')
request.post(
{
url : getDataUrl,
form:jsstringData,
headers : {
"Authorization" : auth
}
},
function (error, response, body) {
if (error){
console.log("There was an error:", error);
} else {
console.log("Request posted successfully!", JSON.parse(body));
}
// res.send(jsonData.jobs[0].id)
}
);
});
Error
SyntaxError: Unexpected end of JSON input [1] at Object.parse
(native) [1] at Request._callback
(/home/tony/Desktop/ng2KnimeUI/dist/server/routes/api.js:49:62) [1]
at Request.self.callback
(/home/tony/Desktop/ng2KnimeUI/node_modules/request/request.js:188:22)
[1] at emitTwo (events.js:106:13) [1] at Request.emit
(events.js:191:7) [1] at Request.
(/home/tony/Desktop/ng2KnimeUI/node_modules/request/request.js:1171:10)
[1] at emitOne (events.js:96:13) [1] at Request.emit
(events.js:188:7) [1] at IncomingMessage.
(/home/tony/Desktop/ng2KnimeUI/node_modules/request/request.js:1091:12)
[1] at IncomingMessage.g (events.js:291:16)

Categories