req.body of post router contains new line and colon? - javascript

I would like to know how to extract the post data from req.body.
My post data is
{
name:'asdf',
completed: false,
note: 'asdf'
}
When I am trying to console it using JSON.stringify , I am getting req.body as
{"{\n name:'asdf',completed:false,note:'asdf'}":""}
I noticed that new line and colon are getting added to the req.body object. So when I am trying to filter req.body.name its returning me undefined.
I have used app.use(bodyParser.json());but still I am not getting the actual result
Hence I would like to know the following:
1. How to filter the post object?
2. Why new lines and colon are getting added to req.body object?

I found solution myself by following
req.body empty on posts
As I am testing in rest-client, The mistakes I did are,
I initially made content-type:www-form-urlencoded. Then later I made it as application/json
I didnt use quotes for key in key-value pair. so you need to pass data in raw section as
{"name":"asdf",
"completed":false,
"note":"asdf"}
Note: Though www-form-urlencoded also work, when you are passing data in form section as
name asdf
completed false
note asdf

All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))

Related

Parsing a URL query object in node.js

I need to create a function that will use an object passed in the url. The goal is to update menu items for a restaurant. The query sent will look like this:
?restId=1&posId=1&groups=…&items= [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]&pizzas=[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]
When I run const queryObject = url.parse(req.url,true).query; it prints:
[Object: null prototype] {
restId: '1',
posId: '1',
groups: '…',
items: ' [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]',
pizzas: '[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]'
}
My problem is that I cannot access any of the values in items. I was given this url, so I cannot change it at all. How can I parse items in order to access the values?
The value of items and pizzas are both JSON formatted strings. You have to parse them to access the contained data. This is accomplished by calling JSON.parse()
So in your case, to access items, you could do the following:
const items = JSON.parse(queryObject.items)
The only problem you have now is that items isn't actually a valid JSON string. It's missing four closing tags }]}] at the end. I'm not sure if that's a transcription error or if you're actually getting a malformed URL, but that will cause you issues if the URL in your question is accurate.

Setting dataType JSON in aws-sdk for sqs

Im just trying to send a json object to sqs queue by using aws-sdk npm package.
const sqsMessage = {
MessageAttributes: {
"data": {
DataType: "String",
StringValue: payload.data
}
},
MessageBody: JSON.stringify(payload),
QueueUrl: queueUrl
If i pass json object in data attribute it tells it expected String, if i add Json then it also throws an error about type, does anyone know a workaround or what to use to get the json?
Some useful links i've found,
1)https://blog.chrismitchellonline.com/posts/aws-sqs-message-with-attributes/
https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-send-message.html
Would really appreciate some guidance on this
Can you share the error message that you're receiving. And can you show us an example of payload that you're constructing? Basically, the allowable values for dataType are found here: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_MessageAttributeValue.html
Specifically, this part: "Amazon SQS supports the following logical data types: String, Number, and Binary. For the Number data type, you must use StringValue."
So when it comes to constructing the value for your key MessageBody, you want to use JSON. So the type must be string and your value, it has to be valid JSON that's really a string and the inner quotes escaped. So for example, something like this:
"{\"foo\": \"bar\"}"
I ran into this same issue while writing unit tests in goLang and it works. I know this is 11 months later, but hopefully this helps you or someone else in the future :)

Taking JSON and working with individuals pieces of information within the JSON

I have an Express App that is being fed JSON data, when I req.body the data I get this:
{ '["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]': '' }
In the end I need to get this into my RethinkDB database, but right now I am trying to just console.log the "A" I have tried req.body[0] and it is showing undefined. I am a little confused about the fact that there are ' ' around the array. I am not sure where the : '' comes from at the end of the JSON but for now I just need the main values in the array.
FYI I am using papaParse to parse a CSV to JSON which is how this data is being sent to my express app. Then fetch is being used to send the data with 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' as the header.
The JSON is structured differently then you think.
Your JSON:
{
'["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]': ''
}
so req.body[0] wont work, the key is the array which is what you need and the value is just an empty string.
should be something like this:
{
'result': '["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]'
}
req.body.result[0] // -> "A"

Accessing JSON data when response contains both JSON data and text

Initially the content from the server was JSON data.And I was able to access the data perfectly.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Now the response from the server has been changed to json data + text data.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Properties for service:
=======================
ServiceEndpoint: https://somedomain:1200/web/Servlet/SOAP/Services
Certificates: false
DocumentName: note.pdf
So whether changing the content-type to application-text and using split method is the only way we can solve this or Is there any better approach?
As mentioned in the comments, mixing JSON and pure text data is wrong (as it defeats the advantage of using standardized data format) and should be avoided. Maybe that is some kind of debug log that was accidentally included in the production code?
If not, you should read just the first line of response and parse it as JSON data, ignoring the rest, hoping for no more changes in response structure ;)
You really should overthink your API design.
What about adding the text part as part of your JSON?
{
... // your JSON properties here
"serviceProperties": { // properties for service
"ServiceEndpoint": "https://somedomain:1200/web/Servlet/SOAP/Services",
"Certificates": false,
"DocumentName": "note.pdf"
}
}

extract specific part of API response to JSON object in Javascript

I am trying to interrogate an API response from the Recognize (fashion recognition) API. The data is returned as set out below. I am trying to extract the items of attire from the following object.
Object {data: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}", status: 200, headers: function, config: Object, statusText: "OK"}config: Objectdata: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"headers: function (name) {status: 200statusText: "OK"__proto__: Object
I have tried to access using data.data which returned the following as a string:
" Array
(
[id] => 1309
)
{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"
I then tried to use JSON.parse to extract the data from the VufindTags. That did not work.
Is there a way to convert this into a JSON Object??
Thanks for any help!!
It looks like the vufind API is giving you PHP print_r output instead of JSON. The best thing to do would be to get them to fix their API. Failing that, you can pull the JSON-ified bits out. I had some success with this:
myObj = JSON.parse(apiOutput.slice(apiOutput.indexOf('{')))
...but I wouldn't put that into an app and call it production ready, especially when the API clearly isn't giving you what it should in the first place.

Categories

Resources