The data can be inserted into the database and the JSON also can be generated very well but why is 'Unexpected token < in JSON at position 1' thrown?
The problem has been shown in the picture
signup.ts
signup(){
this.authService.postData(this.userData,'signup').then((result) => {
this.responseData = result;
if(this.responseData.userData){
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
this.navCtrl.push(LoginPage);
}
else{ {swal({
title: "User already exist.Please try again",
})
} }
}, (err) => { ;
// Error log
});
}
You're getting BR tag in your response, and because of that it can't be parsed to JSON, so remove the
> <br />batman2#gmail.comhere
tag from your response.
You can validate JSON response in your service by using rxjs map operater:
this.http.get(YOUR_URL).map(res => res.json());
Related
I build an Angular app and when I try to make a POST request to my server(REST API with PHP) I get this error, but When I send request from Postman, everything is OK and I can see the result and absolutely its a valid JSON. note that all GET requests works properly.
in my component:
checkUser($username,$password)
{
this.webservice.Check_User($username,$password).subscribe((response) => {
this.results=response;
},(error) => {
console.error('Request failed with error:'+error)
}
);
}
in my service:
Check_User($username,$password):Observable<any>
{
console.log('Request is sent!');
let body = new HttpParams()
.set('checkUser','checkUser')
.set('username', $username)
.set('password', $password);
return this.http.post(this.Base_URL,
body.toString(),{
headers: new HttpHeaders()
.set('Content-Type', 'multipart/form-data')
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Credentials',' true')
.set('Access-Control-Allow-Methods','*')
.set('Access-Control-Allow-Headers','*')
}).pipe( map(results => results)
,
catchError((err) => {
console.log('error caught in service')
console.error(err);
return throwError(err); //Rethrow it back to component
})
)
}
I also tested various types of 'Content-Type' and 'responseType' in header, but still got error.
http response(body and header):
[{"fldUsername":"user","fldPassword":"password","fldName":"fldname","fldLname":"fldLname","fldCreatedate":"2021-01-04","fldCreatedtime":"19:17:29"}]
Content-Type:text/html; charset=UTF-8
Content-Length:181
Access-Control-Allow-Headers:*
Access-Control-Allow-Methods:*
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
X-Powered-By:PHP/7.3.12
Server:Apache/2.4.41 (Win64) PHP/7.3.12
thanks for any help
I'm trying to ask for a confirmation before upload the file so the server, currently I have this HTML code:
<p-fileUpload mode="basic" name="file" url="{{urlUpload}}" chooseLabel="Upload CSV (onBeforeSend)="onBeforeSend($event)">
Then, I have this TS code:
onBeforeSend (event): void {
const token = this.service.getTokenSession();
event.xhr.setRequestHeader('Authorization', 'Bearer ' + token);
this.confirmationService.confirm({
message: 'Are you sure to continue?',
header : 'Confirmation',
accept : () => {
this.service.showLoader();
this.onUpload(event);
},
reject: () => {}
});
}
onUpload(event): void {
this.msgsPage = [];
try {
const response = JSON.parse(event.xhr.response);
console.log(response)
if (!response.ok) {
this.errorModalService.show('There was an error');
this.flagResultLoadErrors = true;
let c = 0;
for (let msg of response.map.errors) {
c++;
this.msgsPage.push({
detail : msg,
severity: 'error',
summary : 'Error ' + c,
});
}
}
} catch (e) {
this.errorModalService.show('Unknown error');
console.log(e)
} finally {
this.service.hideLoader();
}
}
With this, I tried to block the request, but it didn't happen, what I got is that the file is sent to the server before the confirmation dialog.
Also, I'm getting this error when I tried to get the response:
SyntaxError: Unexpected end of JSON input
Hope you can help me.
You can't block from that event. It is just an event emitted from the component.
https://github.com/primefaces/primeng/blob/master/src/app/components/fileupload/fileupload.ts#L367
You will need to use the custom uploadHandler.
<p-fileUpload name="myfile[]" customUpload="true" (uploadHandler)="myUploader($event)"></p-fileUpload>
myUploader(event) {
//event.files == files to upload
}
SyntaxError: Unexpected end of JSON input
This one means the response you are getting from the xhr response is not JSON, but you are trying to parse it. Check network tab to see what the response from the server is.
I have validated my JWT on jwt.io
But when i try to parse the response to:
login(model: any) {
return this.http
.post(this.baseURI + 'login', model, this.requestOptions())
.map((response: Response) => {
const user = response.json();
if (user) {
localStorage.setItem('token', user.token);
this.decodedToken = this.jwtHelper.decodeToken(user.token);
console.log(this.decodedToken);
this.userToken = user.token;
}
})
.catch(this.handleError);
}
it throws an error stating:
Error is generated when it tries to parse response to json: response.json();
A little help would be appreciated.
Since the token starts with e and your error states that its getting an unexpected e at position 0 of what it expects to be a Json document, it sounds like you might be getting a response body including the token as raw text, not the Json User object which your code expects.
I'm trying to get a json from "nightmare" in Node.js and then use JSON.parse(), but I'm getting the following error:
(node:9748) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token ☻ in JSON at position 18509
My code:
var nightmare = Nightmare()
.goto('URL')
.wait(10000) // Need wait some time
.evaluate(() => {
return document.body.innerText;
})
.end()
.then((body) => {
var data;
try {
data = JSON.parse(body);
} catch(e) {
console.log(e);
}
callback(null, data);
});
You can check if the JSON is valid or not simply using the JSON.parse function as you are using.
function validJSON(str) {
try {
// try to parse the JSON
JSON.parse(str);
} catch (e) {
// if not a json
return false;
}
// if it's valid json
return true;
}
It'll check if the string is valid json or not. Now, you can use it with your nightmareJS.
const nightmare = Nightmare()
.goto("URL")
.wait(10000) // Need wait some time
.evaluate(() => {
return document.body.innerText;
})
.end()
.then(body => {
// if it's a valid json, send it,
// otherwise send it as a body object
const data = validJSON(body) ? body : { body };
callback(null, data);
});
Now, the error is showing because you said to catch(e) and console.log(e) the error. Thus it's simply obeying your command.
Since the emoji itself is not a valid json, you have to either make a json from it, or parse it if it was a json string.
A valid json object might look like this,
{emoji: "☻"}
You see how it's all quoted?
I am using angular 4.2.6 for my application. I have a service like this
checkStaff(email: any) {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email)).map(
(resp) => resp
)
}
checkStaff(email:any){
return
this._http.post(this.url+"/Impsapi/getStaff",JSON.stringify(email)).map(
(resp)=> resp
)
}
this.loginServ.checkStaff(this.user)
.subscribe(
userData => {
this._return = userData;
console.log(this._return);
}
);
The Server returns JSON as response. but when i log the output, i get the below
logged response
please I need to consume the data in the body of the response. I have not been able convert the ._body to a proper json and use for the app. please help
The response data are in JSON string form. The app must parse that string into JavaScript objects by calling res.json().
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email)).map(
(resp) => resp.json()
)
Update
try following code snippet
checkStaff(email: any) {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email))
.map(res => {return res.json()})
}
Try this:
this.loginServ.checkStaff(this.user)
.subscribe(
userData => {
this._return = userData.json();
console.log(this._return);
}
);
I mean your checkStaff:
checkStaff(email: any): Observable<Response> {
return this._http.post(this.url + "/Impsapi/getStaff", JSON.stringify(email));
}
export classMyResp
{
id: string;
/*so on...*/
}
This will give you the body of response If there is any.
I got my problem solved. My PHP is hosted on wampserver. In a way invalid JSON is always returned when i make call to the server. I had to use the ob_clean() function and everything is fine.