Handle raw JSON string with node and express - json

I have a really simple endpoint defined in NodeJS using Express:
router.put("/test", this.test.bind(this));
public test(req: Request, res: Response, next: NextFunction) {
console.log(req.body);
}
The endpoint is working correctly if I PUT the following JSON body:
{
"name": "something"
}
However, if I use a JSON body without curly brackets (which is totally valid) like this:
"something"
I get an error:
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:558:11)
Content-Type in both cases is application/json.
Why are these raw JSON strings not getting accepted and how can I solve this?

Related

Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSON

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong.
I looked up similar questions but the solution I adopted to my problem did not work.
My function looks like this:
postData(number){
let array = JSON.stringify(this.locArr);
return this.http.post<any>(this.url, array)
.subscribe(),
error => console.log("Error: ", error)
}
JSON which is send:
[
{
"id":222,
"name":"Lars",
"sLA":37
},
{
"id":223,
"name":"Sim",
"sLA":12
}
]
All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json.
I wonder why this error is occuring.
Any advice is appreciated
The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.
postData(number){
this.http.post<any>(this.url, this.locArr)
.subscribe((data)=>{
//code after receiving data from server
},
error => console.log("Error: ", error))
}
I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []
postData($locArr){ // pass the array to the service function
let data = { data : $locArr}; // note that you have to post it as json object {} not []
return this.http.post<any>(this.url,data);
}

Bad Request response when passing a JSON in process variables - flowable

I'm using flowable and try to pass a JSON as body, but it's seen as malformed when processing the request (or so I think since the error is Bad Request). Basically I'm passing some parameters this way:
#PostMapping(path = PathConstants.START_ACTION)
public ResponseEntity<BaseResponse<ProcessInstance>> start(#PathVariable String processDefinitionId,
#RequestBody(required = false) Map<String, Object> params)
The params are set using postman, this way:
{
"body": {
"email":"testmail#test",
"password":"password"
}
}
The process starts and the POST call is made, but Bad Request is given back. I've tried printing the variables of the process after this call and this is what I have:
body={email=testmail#test, password=password}
So I've tried passing this instead:
{
"body": "{ \"email\":\"testmail#test\", \"password\":\"password\"}"
}
And when printing the variables I have:
body={"email":"testmail#test", "password":"password"}
but still it's a bad request. What is wrong with this JSON?
If you want to pass a variable that is a JSON then you would need to make sure that body is type JsonNode from Jackson.
Looking at your request signature Map<String, Object>, Jackson would contain a map of maps.
I don't know what you are trying to do. However, I would highly advise you to work with predefined parameters in your REST API. If you need something generic you can use the REST API of Flowable to do what you want to do.

How to pass a JSON string to API Gateway as query Parameter

How can i pass a JSON object like {val: 1} to my Lambda function as a query parameter?
Following Standardized way to serialize JSON to query string? i URL-encoded my JSON object and requested the following: mysite.com/path?json=%7B%22val%22%3A%201%7D
As requestTemplates i tried the following two options
"json": "$input.params().querystring.json"
"json": "$util.parseJson($input.params().querystring.json)"
But i got this error message:
{"message": "Could not parse request body into json: Unexpected
character (\'v\' (code 118)): was expecting comma to separate OBJECT
entries\n at [Source: [B#37a2970e; line: 1, column: 47]"}
If i do not encode the query string so: mysite.com/path?json={"val":1} i get a 400 error
Your mapping template is producing no valid JSON, you have to wrap the key/value pair in curly braces
I guess you do not want to wrap the value in quotes, it will be a string and no object otherwise
You can use $util.urlDecode to decode URL encoded strings
Your mapping template should look like this:
{"json": $util.urlDecode($input.params().querystring.json)}
For mysite.com/path?json=%7B%22val%22%3A%201%7D this mapping template will result in the following JSON:
{
"json": {
"val": 1
}
}
If you want the querystring JSON to be passed on the root level to your Lambda function use this as a mapping template:
$util.urlDecode($input.params().querystring.json)

Response JSON object or JSON.stringify?

Suppose I want to return JSON content
var content = {
a: 'foo',
b: 'bar'
};
What is the best practice to return my JSON data?
A) Return object as is; i.e res.end(content)?
B) JSON.stringify(content) and then call JSON.parse(content) on the client?
The client must always send a string. That's what the protocol says. After all, HTTP is a wide-ranging protocol, and not all languages support JSON objects, let alone JavaScript data.
If you don't convert it to a JSON string, chances are that pure Node will just send it as [object Object], and i'm sure that's not your intention.
As mentioned previously, Express lets you send an actual JS object, and does the JSON string converting for you. Alternately, you can manually convert it.
If you send the response with express's res.json you can send the Object directly as application/json encoded response.
app.get('/route/to/ressource', function(req, res){
var oMyOBject = {any:'data'};
res.json(oMyOBject);
});

Backbone.js .save() JSON response attribute issue

So my issue is this.
Using backbone to save something in a MYSQL Database.
When I call this.model.save() I am getting a very weird issue.
The model will save the JSON response as an object and will not update the new values instead.
So my attributes in development tools will look something like this.
attributes: Object
0: Object
ID: "4"
Name: "TEST"
Title: "MEOW"
Stuff: "1"
When: "2013-02-14 22:17:14"
The 0 should not be there. I did confirm that the json object is valid so I know that is not the issue here.
It looks like your JSON response is actually an array with a single element, not an object.
The property 0 is created when Backbone calls model.set(response), which in turn copies all keys of the response object to the attributes hash. If an array is passed to set, this is what happens.
You should fix your server to respond with a raw object ({...}) instead of an array ([{...}]). If you're not able to change the server behaviour, you can override Model.parse to unwrap the response on the client:
var Model = Backbone.Model.extend({
parse: function(response) {
return _.isArray(response) ? response[0] : response;
}
});