res.json converts object into array nodejs - arrays

I'm responding with a JSON in my routing with the following
app.get('/loginerr', function(req, res, next){
var message = req.flash('signupMessage');
res.json({'error' : message});
});
The message is a simple String type but the JSON object is sent inside an array like this:
{
"error": [
"The email is already taken"
]
}
As you can see there is a pair of brackets for an array in the response. How I get rid of them?

you can use this :
var message = req.flash('signupMessage')[0];
res.json({'error' : message});

I was not aware that the req.flash object is an array.
I just had to take the only and first element of the array:
res.json({'error' : message[0]});

Related

getting API response [JSON like] but getting problem while parsing

my API is responding as below
{"permissions":
[{"id":1,"product_id":10,"permission_type":"ADD","name":"Add"},
{"id":2,"product_id":10,"permission_type":"UPDATE","name":"Update"},
{"id":3,"product_id":10,"permission_type":"DELETE","name":"Delete"}
]
}
when i use code
const {
states: { permissions },
}:any = useUMSStoreContext();
const myJSON = JSON.stringify(permissions);
console.log('JSON format', myJSON)
I need to get elements like name or permission_type but not getting success using Typescript. I might be picking wrong way to convert into JSON.
Don't use stringify, just use the json object
const myJSON = JSON.parse(permissions);
console.log(myJson[0].permissions[0].name); // removed . typo
Simple explanation of format :
https://www.json.org/json-en.html

Find Object Array and its Properties from Ajax Post Request

I'm sending an AJAX request to an internal PHP and receiving back an object. The object has properties of "data" and "status", yet when I try to access them, it does not return anything. How can I show each property separately?
For reference, the returned obj array is:
{"data:[{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}]
function GetAll() {
var PostRequest ={};
PostRequest['tagId']= 'all';
$.post('php here',PostRequest,ShowAllTags);
}
function ShowAllTags( responseData, responseStatus ) {
console.log(responseStatus);
var tagData = {};
tagData = responseData;
console.log(tagData['data']);
}
So according to the above comment mention by me, The problem is with json object, in response.
So first of all fix that,
Generic solution of this problem will be;
var obj = [{"tagId":"8787","tagDescription":"001","tagMin":"0","tagMax":"100"},{"tagId":"8729","tagDescription":"1","tagMin":"44","tagMax":"555"}];
obj.forEach(function(value, index){console.log(value.tagId)});
This might help, how to get value of each property

Sending json object as json array to an API

I have an API that accepts data format as [ { "record_id": "TestID3" } ]. I am trying to send record_id field using the form below in my angular project:
html:
<input id="record_id" type="text" class="form-control" [(ngModel)]="member.record_id" name="record_id" #record_id="ngModel" placeholder="Enter Record ID">
component.ts:
export class MembersAddComponent implements OnInit {
member: Array<Object> = [];
constructor(private service: DataService ) { }
ngOnInit() {
}
submit() {
this.service.importRecord(this.member).subscribe(member => {
this.member = member;
}, error => {
console.log(error);
});
}
}
And my service.ts:
importRecord(data): Observable<any> {
const formData = new FormData();
formData.append('token', this.token);
formData.append('content', this.content);
formData.append('format', this.format);
formData.append('returnFormat', this.returnFormat);
formData.append('type', this.type);
formData.append('overwriteBehavior', this.overwriteBehavior);
formData.append('forceAutoNumber', this.forceAutoNumber);
formData.append('data', data);
formData.append('returnContent', this.returnContent);
return this.http.post(this.baseUrl, formData).map(res => res.json())
.catch(this.handleError);
}
The error that I get is below:
{"error":"The data being imported is not formatted correctly. The JSON must be in an array, as in [{ ... }]."}
I also tried member:any = {}, member:Object = {}; but I got the same error. I am thinking that I am unable to format my member object as requested format. But I couldn't make it as desired format.
[ { "record_id": "TestID3" } ]
That is an array, containing a single element, which is an object.
member: Array<Object> = [];
that defines an array with no element at all.
[(ngModel)]="member.record_id"
That will try to read and write the property record_id of member, which is an array. It will not magically add an element to the array and set its property.
So what you need is an object that will be populated by the form. And then you need to put that object into an array before to send the array to the API.
Start by defining an interface to describe your object:
interface Member {
record_id: string;
}
Then use one as the model for your form:
member: Member = {
record_id: '';
};
...
[(ngModel)]="member.record_id"
Then put that member into an array before sending it:
submit() {
const data: Array<Member> = [this.member];
this.service.importRecord(data)...
It's difficult to tell if this is due to an incorrectly formatted response from the POST or the body of the POST.
Things you can do:
Check the network tab in Chrome to verify that the request is being sent, it's content is valid JSON (use an online validator)
Check your API backend to see if the data you're sending is being saved, if so the error is with the format of the JSON in your response.
Verify in Chrome that the response data in the network request is valid JSON.
If all of these are true, you may need to consider using headers such as {requestType: 'json'} as detailed in the Angular docs here: Request/Response Headers
If these are not true, then you will need to change the model of the object you are sending to reflect the object which is expected.

Required String parameter 'licenceplate' is not present"

I checked in different existing questions that was asked for similar problem but I didn't get any help for my problem.
In fact I can't use #RequestBody like in this question or this one.
I'm trying to pas some parameters from Angular controller to a Spring MVC controller, but I'm getting this error message
errorCode:500
message:"Required String parameter 'licenceplate' is not present"
here is my Angular Service:
myApp.httpEnterVehicle = function(levelNumber, placeNumber, licenceplate, placeType) {
return $http.put("/myApp/rest/vehicle/entervehicle", {
params : {
'licenceplate' : licenceplate,
'placeType' : placeType,
'placeNumber' : placeNumber,
'levelNumber' : levelNumber
},
});
};
and nothing was detected on my backend side wich seems to be strange
#RequestMapping(value = "/entervehicle", method = RequestMethod.PUT)
public ResponseEntity<Void> enterNewVehicle(#RequestParam("licenceplate") String licenceplate, #RequestParam("placeType") String placeType, #RequestParam("levelNumber") int levelNumber, #RequestParam("placeNumber") int placeNumber){
....
}
do you have any idea what's going on? I already tried toc check the content of my Angular service param and they are correct :(
You have incorrect put request call, it should look like below
$http.put('url', //1st parameter
{}, //request body
{} //request configuration here
);
If you compare you current put call you can see what wrong thing you were doing. You just need to pass {}(empty object) in request body the pass your config object in place of request body
myApp.httpEnterVehicle = function(levelNumber, placeNumber, licenceplate, placeType) {
return $http.put("/myApp/rest/vehicle/entervehicle",
{}, //added blank object as request body
{
params : {
'licenceplate' : licenceplate,
'placeType' : placeType,
'placeNumber' : placeNumber,
'levelNumber' : levelNumber
},
});
};

node api not receiving json data

I am using angular to call into a node get api. "undefined" is being received by node for req.query.reqdata Am I supposed to parse the JSON on the server side? Any help will be greatly appreciated.
Client:
function playOrError(instrument, octave, scaletype, basenote) {
var reqdata = {
"instrument" : instrument,
"octave" : octave,
"scaletype" : scaletype,
"basenote": basenote
};
$http.get("/api/getfile", reqdata)
.then(
function(response) {
console.log("File request: " + response.data);
},
function(error) {
console.log("File request failed: " + error);
});
}
Server:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
...
app.get('/api/getfile', function(req, res, next) {
console.log(req.reqdata)
var instument = req.query.instrument
console.log(instrument)
})
reqdata is only the variable name you are using on the client side, and is never seen by express. Rather, console.log(req.query); should log an object (which is the reqdata object you pass into it); This object should have the values you added to that reqdata object, like so:
{
"instrument" : instrument,
"octave" : octave,
"scaletype" : scaletype,
"basenote": basenote
}
Then you can get the instrument for example by doing req.query.instrument
This is similar to when you pass a variable into a function. Just because the variable is named something when you pass it as an argument doesn't mean the function will use the same name! In this case, reqdata is passed in as the req.query
I figured this one out. Bennett was close, but it needs the first value to be params. This way you can send a whole bunch of query parameters via object notation.
$http.get("/api/getfile", {params : reqdata})
I also ended up converting te GET into POST eventually.

Resources