Is there any way to convert res object in nodejs to JSON object
app.post('/validateUser', function (req, res)
{
console.log('in post validateUser');
var usr = req.body.usr;
var pwd = req.body.pwd;
//like this
callSomeFunctionOrWebservice(JSON.stringify({data:req.body, respVar:res}));
// the above function gave me error //TypeError: Converting circular structure to JSON at
});
what I need is to convert the entire thing to JSON, pass the arguments and retrieve the arguments on the other function maybe call a web service
I checked out flatted, but I don't know how to encode with flatted
I tried this
var flt = require('flatted');
//JSON encrypt
flt.stringify({data:req.body, respVar:res});
//JSON parse
flt.parse(varData);
But I couldn't get it to work. Can someone helps me or point me in the correct direction?
You no need convert res to json it is already in json object only.
So
var new_object = {data:req.body, respVar:res}
or if you want combine both
var new_object = {...req.body,...res}
console.log(new_object)
Check that it can accessible like json only
Related
const df = require("durable-functions");
module.exports = async function (context, req) {
const client = df.getClient(context);
context.log(`Function Name = '${req.params.functionName}'.`);
context.log(`Body = '${req.body}'.`);
const instanceId = await client.startNew(req.params.functionName, undefined, req.body);
context.log(`Started orchestration with ID = '${instanceId}'.`);
return client.createCheckStatusResponse(context.bindingData.req, instanceId);
};
I have tried to use POSTMAN or https://reqbin.com/ for testing but I always get object.
It is a simple case but I don't understand why it is not JSON object.
I read this one
TypeScript Azure Function Read Body of POST method as JSON
but it didn't help me.
Everything is fine!
It is already deserialized json object.
It looks like the normal string in a log after
JSON.stringify(req.body)
My fault was that I wrongly got it in the orchestrator function from the context.
I'm sending a post request to a cloud function which contains the following body:
{message: "this is the message"}
If I try to print the entire body of the request, it shows it, but if I try to get the message field, I get undefined in the console.
Here's my function:
exports.myCloudFunction = functions.https.onRequest((req: any, res: any) => {
console.log(req.body)\\prints the body of the request fine
console.log(req.body.message)\\prints "undefined"
cors(req, res, () => {
const pl = req.body.message;
console.log(pl);\\prints "undefined"
});
return res.send("all done")
});
You don't need a body parser for Cloud Functions as described in the other answer here. Cloud Functions will automatically parse JSON and put the parsed JSON object in the body attribute. If you want this to happen automatically, you should set the content type of the request to "application/json" as described in the linked documentation. Then you can use req.body as you'd expect.
I personally haven't worked with firebase before, but from your code and the fact that req.body prints the body, it seems that you probably need to parse the request-body as json in order to be able to access the message property:
const body = JSON.parse(req.body);
console.log(body.message);
It could also be the case that you need to setup a bodyparser for json content. In a normal express-app you can do this using (note that you don't need the manual parsing from above anymore using bodyparser):
const bodyParser = require('body-parser');
app.use(bodyParser.json();
EDIT:
see Doug's answer for the correct way to do this, i.e. to fix your request and set the content-type to application/json in order for Cloud Functions to automatically parse and populate req.body with the request body.
You need to just convert the request body into a JSON object in cloud function.
const body = JSON.parse(req.body);
// message
console.log(body.message)
I'm using node.js.
I've managed to load and parse my .json file using async.
The whole concept is very new to me, I can see my .json data in console but I'm not really sure how to actually use my data now,..
async function getJsonFile() {
let response = await fetch('example.json');
let responsejson = await response.json();
let str = JSON.stringify(responsejson);
let jsonData = JSON.parse(str);
return jsonData;
};
getJsonFile().then(console.log); // I see my .json file in console, how can I use it ?
}
I think that's the way to do it:
var json = await getJsonData();
// use it
If you are trying to use your data which is inside your json you can do this :
// Use this in an async function
const data = await getJsonFile();
// Then get value of one key
console.log(data.key); // from {key: "value"}, you'll get value
To actually use what is in the JSON you need to store it as a variable and then access it in ways that are useful to you. You can access properties of objects using property accessors.
// Save as variable
var json = await getJsonData();
// Do something with properties of data
console.log(json['key']);
I'm creating a website scraping API, and sometimes there are special characters, often in names, eg. "Jesús M.Vargas".
My API downloads website content using request library and passes page's body to cheerio like this: const body = cheerio.load(page);
Then, I try to find text on the page, I know it's always the first <b>: var copyright = body('b').eq(0).text().trim();
Next, my code adds everything (like title, copyright, etc) to an object ({}) using pieces of code like data["copyright"] = copyright;
The last thing is to return the object to user as JSON object:
app.get("/api/", (req, res) => {
res.setHeader('Content-Type', 'application/json');
// query parameters
const date = req.query.date;
.
. // get the webpage, find the data, add everything to an object
.
// get the data from `data` object and return it as JSON
var output = JSON.stringify(data);
res.send(output);
}
When the API returns text like in the example above, "Jes�s M.Vargas" is visible in the JSON file. Is there a way to fix these characters? For stringifying object I'm using vanilla JavaScript, my web framework is Express
I'm trying to use breeze.js with sails.js.
Therefore I'm using the breeze json uriBuilder.
I logged the req.query and got the following:
{ '{"where":{"name":"foo"},"orderBy":': { '"name"': '' } }
To query waterline objects I need to bring it into a format like this:
{ where: { name: 'foo' }, sort: 'name' }
First thing I tried:
var queryString = JSON.parse(Object.keys(req.query)[0]);
That works as long as I only put a where clause in. But with more parameters i get this strangely formatted json object.
How can I parse it to get the correct object?
Solution:
Don't parse he req.query. Parse the url and parse it. This way u will get a json uery that sails accepts. Now strip of unsupported parameters as select and you're done.
var parsedUrl = urlUtils.parse(req.url, true);
var jsonQueryString = Object.keys(parsedUrl.query)[0];
var jsonQuery = JSON.parse(jsonQueryString);
Good question! We haven't yet documented this adequately, but the basic idea is that there is a breeze-client npm package (https://www.npmjs.com/package/breeze-client) that you can use to parse the incoming json query into a breeze EntityQuery instance, from there you can interrogate the EntityQuery and turn it into whatever server side syntax you want, i.e. in your case Sails.)
// req = the HTTP request object.
var resourceName = req.params.slug; // the HTTP endpoint
var entityQuery = breeze.EntityQuery.fromUrl(req.url, resourceName);
// you would write the transform to sails below.
var sailsQuery = tranformToSails(entityQuery);
This is exactly what we do in the breeze-sequelize npm package where we take the incoming req.query and go thru the process above to create a 'Sequelize' query.
See http://www.getbreezenow.com/sequelize-mysqlpostgressql-lite