"XML Parsing Error: no root element found" Ionic/Angular - json

There are many topics with this similar error: "XML Parsing Error: no root element found", but none of them cover the error for Ionic framework.
I am writing an app with Ionic framework, and this is the function to POST the data:
http.ts
postData(url, body) {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const result = this.http.post(url, JSON.stringify(body), {headers: headers})
.map(response => {
console.log(response.json());
response.json();
})
.subscribe(data => {
console.log(typeof(data));
console.log("subscribe data");
},
error => {
console.log(error.statusText);
})
A button on my app's HTML form calls the onSubmit function to send the data like below.
submit.ts
onSubmit() {
var submitData = {
'customer': {
'phone_number': this.clientInfo.phone,
'name': this.clientInfo.name
},
'amount': this.clientInfo.amount
}
const submitResult = this.httpProvider.postData(postTransactionsURL, submitData);
Now, on Firefox, this is the error that is shown in the console:
XML Parsing Error: no root element found
Location: http://localhost:3000/transactions
Line Number 1, Column 1:
As reported in other posts, the error does not show up on e.g. Edge, but nevertheless, there is still a more generic error.
Is there anything I could try to resolve this? I would assume the header is correct for this?
Update: added POST network information from console:
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Fri, 02 Mar 2018 12:42:36 GMT
X-Powered-By: Express
Update2: server.js response
app.post('/transactions', (req, res) => {
......
......
......
res.status(200).send();
} else {
res.status(400).send("Invalid transaction");
}
});

Related

ESP8266 POST request to Firebase Cloud HTTP Function returns Error 500 Could not handle the request

It works fine with Postman but gives me an error when I try it through my ESP8266. Here is the code for the ESP8266:
if(buttonState == HIGH) //send notification when button pressed
{
HTTPClient http;
WiFiClientSecure client;
client.setInsecure();
//client.setFingerprint("A5:D4:06:4C:2A:4B:46:CD:C4:A5:51:7F:4C:F6:62:92:60:90:FD:37");
http.begin(client, notifUrl);
http.addHeader("Content-Type", "Content-Type: application/json");
int httpResponseCode = http.POST(input);
if(httpResponseCode>0)
{
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
}
else
{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
http.end();
}
delay(1000);
}
And here is the Firebase Cloud Function:
exports.sendNotification = functions.https.onRequest((req, res) => {
// Check for POST request
if(req.method !== "POST"){
res.status(400).send('Please send a POST request');
return;
}
console.log(req.body);
var message = {
data: {
title: 'Someone is at the door',
body: 'Always check who it is before unlocking your door :)'
},
android: {
priority: 'high',
},
token: req.body.token
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
res.status(200).send('Message sent successfully');
})
.catch((error) => {
console.log('Error sending message:', error);
res.status(500).send("Error sending message");
});
});
Note the console.log(req.body) in the Cloud Function. I can see the log when trying with Postman but when trying with the ESP chip the function doesn't even reach till the console.log line and just says function exited with status 'crash' in the logs.
I am pulling my hair out here trying to figure out what is going wrong. Any help is appreciated.
The issue here must be because you are sending a wrong HTTP Content-Type header.
You are sending Content-Type: Content-Type: application/json, instead of Content-Type: application/json, I guess Firebase doesn't like it too much!
In your code it should then be:
http.addHeader("Content-Type", "application/json");

Angular login authentication with json rest api

I am trying to make a login authentication in angular, in which when we are entering email id and password we are getting a token. So for authentication, we have to send that header in the api get request but i am not able to do it.
My code is shown below
onSubmit(form:NgForm) {
this.http.post('https://pikreview.com/rest/user.php?f=authenticate',
JSON.stringify({
email: "a#gmail.com",
password: "12345"
})
).subscribe(res => {
localStorage.setItem('token', res.token);
var authToken = localStorage.getItem('token');
console.log("token is " + authToken);
var headers: HttpHeaders = new HttpHeaders({
'token': `${authToken}`,
'Access-Control-Allow-Credentials': true,
});
var req = new HttpRequest('GET',
'https://www.pikreview.com/rest/user.php', {
headers: headers,
withCredentials: true
}
);
this.http.request(req).subscribe(data => {
console.log(data);
})
}, error => {
console.log("something went wrong");
});
}
And one thing i have seen that whenever i pass token header there is something set-cookie generated which has token value on authentication page but on profile page it is not getting the same token and i think therefore it is showing invalid token.So,if anyone knows something about it and can solve my problem,please reply as soon as possible.
You just simple call the api with ur custom header, use HttpHeaders like this:
const httpOptions = {
headers: new HttpHeaders({
'Authorization': "YOUR_TOKEN"
})
}
this.http.get('http://localhost:5000/getUser',httpOptions)

Fetch in react with json always returns an error

For the following created code in react, after I search similar question, I get always an error (seems that the error is return of a promise).
I am using webpack version 3.1.9
In web-pack configuration I did (don't know whether it is necessary):
module.exports = {
...
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": "*"
}
},
...
Here is my code:
var options = {
method: 'get',
mode: 'no-cors',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*'
}
};
let _url = 'my url ... web api returns json';
fetch(_url, options)
.then(response =>
response
.json()
.then(data => ({
data: data,
status: response.status
}))
.catch(err =>
/******ERROR: always catch the error *****/
({ error_data: err })
)
)
.then(res => {
console.log(res);
// console.log(res.status, res.data.title)
})
.catch(err => {
console.log(err);
});
The error in the line with the asterisks, as code above
SyntaxError: Unexpected end of input at eval
The code was checked for restful api in C#:
I did in the controller code:
public ActionResult Index()
{
ActionResult x = Json(db.Trainees.ToList(),
JsonRequestBehavior.AllowGet);
//return Content(db.Trainees.ToList().ToString(),
"application/json");
return Json(db.Trainees.ToList(), JsonRequestBehavior.AllowGet);
// return View(db.Trainees.ToList());
}
I assume it is related to fact that json returns a Promise, as described in: json returns promise
I see that json is problematic. When I change response.json() to response.text() there is no error, but I realize that even I send the options with 'no-cors', I see an information message:
Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json
Seems that the fetch ignore the options with 'no-cors'.
Any clues, why the code encounters an error?!
Thanks.
Problem had been fixed.
In react I did the changes:
var options = {
method: 'GET',
}
...
In C# restfull api controller I did the changes:
Response.AddHeader("Access-Control-Allow-Origin", "*");
return Json(db.Trainees.ToList(), "application/json",
JsonRequestBehavior.AllowGet);

Angular2 HTTP POST An error occurred SyntaxError: Unexpected end of JSON input

I have error meantime angular2 post rest data to NodeJS backend.
I see POST is done, server is LOG correct data, but error is showing up on browser.
An error occurred:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
My NG2 call and service:
onSubmit(form:FormGroup) {
let userform: FormGroup = form.value;
console.log("userform: ", userform);
if (form.valid) {
console.log(form.value);
this.appService.signIn(userform)
.subscribe(form => console.log('subscribe: ', form))
} else {
console.log("Form is not VALID!");
}
}
SERVICE:
signIn(dataUser: Object): Observable<User> {
dataUser = JSON.stringify(dataUser);
debugger;
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://127.0.0.1:3005'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", dataUser, "\nHeaders: ", headers);
return this.http
.post( this.signInUrl, dataUser, options)
.map( (res:Response) => res.json().data || { } as User )
.catch(this.handleError);
}
and nodeJS:
app.post('/login', function (req, res) {
console.log("Recived login request!");
console.log("Request: ", req.body);
res.header({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Accept': 'q=0.8;application/json;q=0.9'
})
res.end();
});
In post we have: "{"username":"username","password":"password"}".
What I'am making wrong? Please for help or solution.
Awwwww. That was my bad, Take care of your NodeJS Server response. After get POST, should be sended any res.json({status: "OK"}) or sommething similar, to get response. This error was not because of Angular2, but because of NodeJS. Browser get empty response from nodeJS, or it was not JSON format.

React-Native Fetch "POST" request throwing "SyntaxError: Unexpected end of JSON input" in Android

this is my function
don't know where is the problem
fetchData() {
fetch(REQUEST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Request : 'menu',
active : '1',
})
}).then((response) => response.json())
.then((responseData) => {
this.setState({
menu: responseData.Response,
});
})
.catch((error) => {
console.warn('error',error);
})
.done();
}
please point out the problem in function
The error occcurs because your response cannot be casted to JSON format. This issue might happen because of wrong header, response body, or other various reasons based on your server. The way to go - since apparently the responses are not consistent - is to perform additional validation of server response before trying to cast the response to JSON.
You can do this by replacing:
.then((response) => response.json())
with
.then((response) => {
// In this case, we check the content-type of the response
if (response.headers.get('content-type').match(/application\/json/)) {
return response.json();
}
return response;
// You can also try "return response.text();"
})
The error will be occcurs because your response can not be casted to be JSON
format.
there are three type of php mysqli api formate
1 formData
2 xml
3 json
i think you are use Formdata api but you are request in json see formdata
example
1) json Request.. example
var Request = {
security:1,
token: token,
email: this.state.username,
password: this.state.password
};
console.log(JSON.stringify(Request));
fetch(API.login, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(Request)
})
.then(res => res.json())
.then(res => {
console.log("Login RESPONCE::: ", res);
}
2)Formdata Example use form data i think your error will be solve
let formdata = new FormData()
formdata.append("Api variable",your post variable)
formdata.append("name",this.state.name)
formdata.append("email, this.state.email)
formdata.append("password",this.state.password)
fetch('http://192.168.1.116/Restaurants/Registration.php', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body:formdata
}).then(res => res.json())
.then(res => {
console.log('Data RESPONCE::', res);
}
then((response) => response.json())
^^^^^^^^^^^^^ I think this is the problem
Responses with status code not equal to 2xx will not go into catch when you use fetch API, therefore you may JSON.parse something such as a HTML page or plain text stream.
You should check if response.ok === true before you parse response as JSON.
The likely cause of this error is your server not returning something that's not valid JSON (likely not JSON at all, like a 404 page or similar).
If you set the request Content-Type to application/json, likely it will send a preflight request to check CORS.
In my React app (not React-Native), I got cross domain issue. My server doesn't support preflight request, and so the response looks like:
{
body: null,
status: 0,
ok: false,
}
which is causing response.json() failed even though I got the expected JSON response in Chrome Dev Tools.
In my case, I change request Content-Type to application/x-www-form-urlencoded which does not require a preflight request. It works as expected.
It might not help in your case but I hope it give you some insight.
Log responseData. It might be possible that API is returning invalid data.