Trying to debug a new React-native application -- pretty large and it has no backend so I am trying to stub something out.
The request format is pretty foreign to me. Does anyone recognize this format or know how to handle it?
proc_name=customer_ref¶ms={"fields" : ["customerId"],"conditions":[{"mailAddress":"dsadsa"},{"pinCode":"ZHNhZHNh"},{"mailReceiveFlag":"1"}],"order" : ["customerCode desc"],"limit" : "1","table_name" : "Customer"}
React-native request code looks like this:
try{
let result = await fetch(apiUrl, {
method: 'POST',
headers: {
'X_contract_id': contact_id,
'X_access_token': access_token,
'Content-Type': 'application/x-www-form-urlencoded',
'charset':'UTF-8',
},
body: 'proc_name='+proc_name+'¶ms={'+params+'}'
}).then((response) => response.json())
.then((responseJson) => {
return responseJson.result;
})
return result;
}catch(e){
console.log(e);
}
The application errors out with Unhandled Promise Rejection before even making it to the server I whipped up. Pretty new here; am I doing something wrong at the frontend layer?
Try changing your fetch structure to be like this.
async functionName(){
try{
let result = await fetch(apiUrl, {
method: 'POST',
headers: {
'X_contract_id': contact_id,
'X_access_token': access_token,
'Content-Type': 'application/x-www-form-urlencoded',
'charset':'UTF-8',
},
body: 'proc_name='+proc_name+'¶ms={'+params+'}'
});
let resultjson = await result.json();
return resultjson.result;
}catch(e){
console.log(e);
}
}
https://facebook.github.io/react-native/docs/network.html
Related
I'm new in JS world and callbacks.
Why I can't return response after then function for the Firebase callable functions?
It returns empty if I return like shown below. I guess it doesn't wait for the response, response has data.output variable actually.
exports.testApi = functions.https.onCall(async(data, context) => {
const formData = new FormData();
formData.append("height", "512");
const response = await axios.post('https://....', formData, {
headers: formData.getHeaders()
})
.then((response) => {
console.log(response.data);
return {'imageURL':response.data.output};
})
.catch((error) => {
console.log(error)
});
}
);
It works with this format
const response = await axios.post('https://..', formData, {
headers: formData.getHeaders()
})
return {'imageURL':response.data.output};
The main attraction of async and await is cleaner syntax, in particular syntax that doesn't use then (opinion). You can mix them but I would always try to avoid it, especially here where the task is so simple.
exports.testApi = functions.https.onCall(async(data, context) => {
try {
const formData = new FormData();
formData.append("height", "512");
// Wait for post to give us a response.
const response = await axios.post('https://....', formData, {
headers: formData.getHeaders()
});
// If we get here, we waited and got a response. Proceed.
console.log(response.data);
return {'imageURL': response.data.output};
} catch (error) {
// If we get here, post threw an error (assuming it throws).
// And we never executed any lines after const response = await...
console.log(error);
}
});
Side note: Firebase Cloud Functions have to be properly terminated and this function does not. For example, if post throws an error and control flows to the catch block then the function will simply timeout because we haven't returned a Promise or thrown a compliant error.
I am developing Cypress tests for my API.
The response from my API in Postman is below:
{"infected" : false}
And my Cypress test is below:
describe("Testing the result after scanning file", () => {
it("Scan file", function () {
//Declarations
const fileName = 'example.json';
cy.fixture(fileName, 'binary')
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
const formData = new FormData();
formData.append("file", blob, fileName);
cy.request({
method: 'POST',
headers: {
'content-type': 'multipart/form-data'
},
body: formData,
url: '/scan'
}).then(response => {
console.log('the response is: ', response.body)
expect(response.body).to.have.property('infected').and.eq(false);
});
})
});
});
In my browser, the Cypress test fails with the message:
assert expected {} to have property infected
I really have already broken my brain with this issue and still have no clue how to tackle it. Can anybody give me an idea what is going wrong?
Try converting the response to json, you may be seeing a string version of the data.
Postman output will not be helpful, it could be converting automatically in the background.
cy.request({
...
})
.then(response => response.json())
// OR
// .then(response => response.body.json())
.then(data => {
console.log('the data is: ', data) // better debug tool than Postman
expect(data).to.have.property('infected').and.eq(false);
});
please, help me check this post request.
I've been looking at it since yesterday, I don't know what is wrong with it
maybe I need another developer's pairs of eyes.
thanks in advance
buttons.addEventListener('click', ()=>{
fetch("https://jsonplaceholder.typicode.com/comments", config)
.then(res=>{
res.json();
}).then(datae=>{
console.log(datae);
})
});
const config = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newName)
}
buttons.addEventListener('click', () => {
fetch('https://jsonplaceholder.typicode.com/comments', config)
.then((res) => {
return res.json()
})
.then((datae) => {
console.log(datae)
})
})
you just need to return res.json()
this should work, but remember that the function you pass to the .then function has access to the returned value from the previous .then.
fetch returns a promise that resolves into an object with the .json function
so in the first .then it will get that object and you need to return res.json() which returns a promise that will be resolved to the JSON data
so in the next .then you can use that data
I hope I was clear
note:
.then function returns a promise ( always )
also maybe you have an error in the config variable, what you pass to the JSON.stringify function should be a valid javascript object
const config = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'rowadz' }),
}
I am using http post for one of my angular application for login.I have checked the url with the params in postman which gives me the output.But when i try to use the same in the application i am getting the error as invalid login all the time.
I would like to know whether the way i pass the params are correct or not?
const formData = `username=${username}&password=${password}`;
const options = { headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) };
return this.http.post<any>(`${this.baseUrl}?action=login&`, formData, options)
.pipe(map(response => {
console.log('user is', response);
if (response && response.session && response.session.id) {
localStorage.setItem('currentUser', JSON.stringify(response));
this.currentUserSubject.next(response);
}
return response;
}));
The error i am getting is
user is {error: "Incorrect Login."}
You can try like this instead of formData
const data = new HttpParams()
.set('username', username)
.set('password', password);
return this.http.post<any>(`${this.baseUrl}?action=login&`, data)
.pipe(map(response => {
if (response.status === 'success') {
localStorage.setItem('currentUser', JSON.stringify(response));
this.currentUserSubject.next(response);
}
return response;
}));
I'm struggling to figure out why the response I get from my API isn't mapping to an object that I have in typescript.
Here's the function in my service that calls the API:
register(user: IUser): Observable<IUser> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var options = new RequestOptions({
headers: headers,
url: this._registerUrl,
body: JSON.stringify(user)
});
return this._http.post(this._registerUrl, { user }, options)
.map((res: Response) => res.json() as IUser)
.catch(this.handleError);
}
This is the function that calls the service:
register(): void {
let user: IUser = {
email: this.email,
username: this.username,
password: this.password
}
this._userService.register(user)
.subscribe(result => {
debugger;
if(result.errorCode > 0)
this.handleError(result.errorCode);
else {
localStorage.setItem('userId', result.userId.toString());
localStorage.setItem('username', result.username.toString());
localStorage.setItem('email', result.email.toString());
}
});
}
The object that I am returning from the API matches the object that I have in the frontend. It is returning the data and I can see it in the body of my response. All of the data is right, but it's in the body and is not turning it into an IUser object.
Does anybody have any ideas? Thanks.
EDIT
This is what the response object looks like when it comes back from the service.