Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to send a json response to a GET call from node js server.
I am creating a json as follows
var request = require('request');
var parseString = require('xml2js').parseString;
env.server.get('localhost:3000/details', function(req, res) {
if (req.query.code) {
request.get({
url: 'http://www.example.com/net2/getDetails?code=' + req.query.code
}, function(err, result, body) {
if (err) {
console.log('error :' + err);
res.status(404).json({
infoMsg: "Error"
});
} else if (result.statusCode == 200) {
var resultBody = {};
parseString(body, function(e, parsedResult) {
resultBody["userName"] = parsedResult.userName;
resultBody["userDept"] = parsedResult.department;
resultBody["userCat"] = parsedResult.category;
res.send(resultBody);
});
}
})
} else {
console.log('Request failed .');
}
});
I am expecting a result which needs to be in this format
{
"name": "test",
"dept": "dept1",
"cat": "cat2"
}
But the response which I am getting is in this format
{
"status": "success",
"data": {
"name": "test",
"dept": "dept1",
"cat": "cat2"
}
}
How to create a response which is in the expected format ie without status and data being added, where am I going wrong.
If you're requesting the JSON with Ajax Request, then the status field is a primordial part of the 'res' and can't be removed.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I got this error when I created api for update but it has array data in it. i am using cloud functions in firebase cli
i use the code below
app.put("/api/update/blog/:id", (req, res) => {
(async () => {
try {
const reqDoc = db.collection("blogdetails").doc(req.params.id);
await reqDoc.update({
title : req.body.title,
author : req.body.author,
kategori : req.body.kategori,
paragraf : req.body.paragraf,
image : req.body.image,
});
return res.status(200).send({ status: "Success", msg: "Data Updated" });
} catch (error) {
console.log(error);
res.status(500).send({ status: "Failed", msg: error });
}
})();
});
I'm currently working on a rest API using nodejs and mongodb, I've found a problem with a request that should bring to me the information based on an id.
I keep receiving TypeError: Converting circular structure to JSON, through many attempts and checking other questions there is no solution.
router.get('/store/:id', async (req, res) => {
const { id } = req.params;
const db = req.app.locals.database;
try{
const result = await db.collection(collection).find({store_id : id }).toArray();
console.log(result);
res.json(result);
}
catch (error) {
res.status(500).json({ error: error.toString() });
}
})
This is the structure of the information coming from database:
{
"_id": "5d1809974f7a7c32cb742f79",
"timestamp": "25-03-2004 21:18",
"store_id": 2,
"user_id": 2,
"product_id": "5d041fa86a8d2c001dad47ba",
"price": 1116
}
I would really appreciate any hint or help and thank you for taking the time to read my question.
I am bulding a messenger bot with node js express.I am trying to split my index.js file into two files. Here is the code for msg.js which is the new file
'const
express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
PAGE_ACCESS_TOKEN ="",
app = express().use(bodyParser.json());
//functions
module.exports = {
//hangles messages
handleMessage:function (sender_psid, received_message) {
let response;
// Checks if the message contains text
if (received_message.text) {
// Create the payload for a basic text message, which
// will be added to the body of our request to the Send API
response = {
"text": `You sent the message: "${received_message.text}". Now send me an attachment!`
}
} else if (received_message.attachments) {
// Get the URL of the message attachment
let attachment_url = received_message.attachments[0].payload.url;
response = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Is this the right picture?",
"subtitle": "Tap a button to answer.",
"image_url": attachment_url,
"buttons": [
{
"type": "postback",
"title": "Yes!",
"payload": "yes",
},
{
"type": "postback",
"title": "No!",
"payload": "no",
}
],
}]
}
}
}
}
// Send the response message
module.exports.callSendAPI(sender_psid, response);
},
// Handles messaging_postbacks events
handlePostback:function (sender_psid, received_postback) {
let response;
// Get the payload for the postback
if (received_postback) {
let payload = received_postback.payload;
}
// Send the message to acknowledge the postback
module.exports.callSendAPI(sender_psid, response);
},
// Sends response messages via the Send API
callSendAPI:function (sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
};
I have the following code at the bottom of my index.js file.
//Imports functions from other files
let msg = require('./msg.js'),
handleMessage = msg.handleMessage(),
handlePostback = msg.handlePostback(),
callSendAPI = msg.callSendAPI();
I am getting the following error:
msg.js:14
if (received_message.text) {
^
TypeError: Cannot read property 'text' of undefined
The problem is this line:
if (received_message.text) {
When this gets called, received_message which is passed in is undefined, so when you try to get the text field from the received_message variable it will throw an error since received_message is undefined and thus would not have any fields you could call from it. Check to see if received_message is ever set properly before being passed into your handleMessage function.
I'm trying to make a client for GroupMe using the API that it provides but I'm unable to figure out what's wrong with what I'm doing.
curl -X POST -H "Content-Type: application/json" -d '{"message": { "text": "Nitin is holding me hostage", "source_guid": "7374"}}' https://api.groupme.com/v3/groups/30885833/messages?token=I_PUT_MY_ACCESS_TOKEN_HERE
I've done that command and it successfully returns:
Click here to see JSON (Hastebin)
My issue is putting this into Javascript code where I've done that like so:
var HTTPS = require('https');
var request = require('request');
function postMessage() {
var options, body, botReq;
options = {
hostname: 'api.groupme.com',
path: '/v3/groups/30885833/messages?token=DbZoE9Eablg43ZIGdfKsFkXDjLzR6RDUkwHT9JNn',
method: 'POST'
};
body =
{ '"message"': { '"text"': "I am a post message", '"source_guid"': "7374" } };
console.log(body);
botReq = HTTPS.request(options, function (res) {
if (res.statusCode == 201) {
//neat
} else {
console.log('rejecting a bad status code ' + res.statusCode);
}
});
botReq.on('error', function (err) {
console.log('error posting message ' + JSON.stringify(err));
});
botReq.on('timeout', function (err) {
console.log('timeout posting message ' + JSON.stringify(err));
});
botReq.end(JSON.stringify(body));
}
But this returns, and only returns Error Code of 400 and I'm not sure how to find the other information relating to why it is a Bad Request.
Essentially, I'm asking how do I transform the command that I gave above to javascript, properly. Thanks!
I believe the issue is how you are defining body like this
body =
{ '"message"': { '"text"': "I am a post message", '"source_guid"': "7374" } };
You end up with an object that literally has the key "message", instead of message.
Try:
body = {"message": { "text": "Nitin is holding me hostage", "source_guid": "7374"}}
I have this nodejs app and one of the calls I've made is an upsert call that upserts the request body to mongodb. If the request body exists in mongo, update it, else insert it. The insert portion works correctly, however, I am having trouble with the upsert portion. My request body is being generated by a C# app that I've written.
Ok, so when I update, I need to use the $addToSet and $each commands because I am adding elements into an array in the mongo document.
Here is an example request body (this is a POST), this is what's sent to my nodejs app:
{
"$addToSet": {
"Data": {
"$each": [
{"ID":"10","RandNum":"45"},
{"ID":"11","RandNum":"1"},
{"ID":"12","RandNum":"3"}
]
}
}
}
The document is formatted like this in mongo:
{
"Timestamp": "timestamp",
"Id": "12345",
"Header": {
"Name": "Name",
"Query": "SELECT * FROM test"
},
"Data": [
{
"ID": "1",
"RandNum": "34"
}, {
"ID": "4",
"RandNum": "23"
}
]
}
I am only interested in inserting into the "Data" array so I am using the $addToSet and $each operators.
This is my upsert call on the nodejs app, the actual function has a lot of code so I'll just put the upsert parts:
var db = require('../db.js');
var ind = require('./index.js');
var mongo = require('mongodb').MongoClient;
exports.upsert = function(req, res) {
var token = req.params.token;
var app = req.params.applicationId;
var dataObject = {
"Status": 1,
"DataObject": {},
"UserFriendlyErrorMessage": "",
"DeveloperErrorMessage": ""
};
// set response header
res.writeHead(200, {"Content-Type": "application/json"});
res.writeHead(200, {"Content-Length": Buffer.byteLength(req.body)});
var upsertDatabase = mongo.connect(ind.mongoLoc + databaseName, function(err, newDb) {
if(err)
throw err;
var upsertCollection = newDb.collection(collectionName);
if(newDb) {
if(req.query.query) {
// UPSERT
try {
var json = JSON.parse(req.query.query);
upsertCollection.update(json, req.body, {upsert: true, multi: false}, function(err, records) {
if(err)
throw err;
console.log("Data updated");
});
} catch(e) {
dataObject["DataObject"] = null;
dataObject["UserFriendlyErrorMessage"] = "Could not update";
dataObject["DeveloperErrorMessage"] = e;
res.end(JSON.stringify(dataObject, 0, 4));
console.log(e);
}
} else {
// INSERT
upsertCollection.insert(req.body, function(err, records) {
if(err)
throw err;
console.log("Data inserted");
});
}
dataObject["Status"] = 0;
dataObject["DataObject"] = null;
res.end(JSON.stringify(dataObject, 0, 4));
} else {
// could not connect to database
dataObject["DataObject"] = null;
dataObject["UserFriendlyErrorMessage"] = "Could not connect to database";
dataObject["DeveloperErrorMessage"] = "ERROR: Could not connect to database";
res.end(JSON.stringify(dataObject, 0, 4));
}
});
};
In this function, I am testing to see if the document exists and then upserting it if it does. That's the part I'm focusing on. The dataObject is what I'm returning to the user to show errors/successes.
When I post the data to this call, I get this error (I'm viewing the POST call in Fiddler):
HTTP/1.1 504 Fiddler - Receive Failure
Date: Fri, 28 Feb 2014 15:30:39 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
Cache-Control: no-cache, must-revalidate
Timestamp: 10:30:39.535
[Fiddler] ReadResponse() failed: The server did not return a response for this request.Server returned 0 bytes
Content-Type is supposed to be application/json
I fixed it. It seems that the line
res.writeHead(200, {"Content-Length": Buffer.byteLength(req.body)});
was not allowing it to post the data. I tried removing it and the upsert worked.
However, I'm wondering why removing that did the trick. I thought that Content-Length was necessary because it specifies the length of the body.