I'm running my app on android emulator on my mac and trying to hit a service endpoint which is deployed on firebase. I'm getting 500 error saying nothing and when I'm trying to print the error it says There was a problem sending log messages to your development environment [PrettyFormatPluginError: value.hasOwnProperty is not a function. (In 'value.hasOwnProperty('tag')', 'value.hasOwnProperty' is undefined)].
When I try to hit the same endpoint using postman and the same payload, I'm succesfully able to do it.
Following code is written in the app
fetch('https://{app_url}.cloudfunctions.net/app/user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: userPayload
})
.then(response => response.text())
.then(result => {
console.log('User in DB created');
console.log(result);
})
.catch(error => console.log('error', error));
Can anyone help me here ?
You're setting Accept: 'application/json', so you should change ".then(response => response.text())" to ".then(response => response.json())". Let me know if it works.
fetch('https://{app_url}.cloudfunctions.net/app/user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: userPayload
})
.then(response => response.json())
.then(result => {
console.log('User in DB created');
console.log(result);
})
.catch(error => console.log('error', error));
Related
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);
});
I am trying to use Drupal Webform REST.
I got an error "The 'restful post webform_rest_submit' permission is required." on browser console. I have enabled modules and REST resources as mentioned.
I used Authorization, the Auth generated in Postman, using basic auth.
I am struggling to use 'x-csrf-token' in postman.
I want to use submit the form by an anonymous user. Do I still need Authorization, will just token not work on same-origin?
const handleSubmit = async (e) => {
e.preventDefault();
await axios({
method: 'GET',
url: `${baseurl.URL}/session/token`,
headers: {
'Accept': 'application/vnd.api+json',
}
})
.then(response => response)
.then((token)=>{
console.log("CSRF TODKEN", token.data);
axios({
method: 'post',
url: `${baseurl.URL}/webform_rest/submit?_format=json`,
headers:{
'Accept': 'application/vnd.api+json',
'Content-Type': 'application/json',
'X-CSRF-Token': token.data,
'Authorization':'Basic $S$EDSnVMXDICYbVGJ'
},
data: {
"webform_id": "contact_form",
"name":name,
"email": email,
"subject": subject,
"message": message
}
})
})
.then(response => {
console.log(response)
response.status === 200 && console.log("Form successfully submitted")
})
.catch(err => console.log("SUBMIT FAIL ERROR ",err))```
It worked. I gave permission to "Access POST on Webform Submit resource" to anonymous users.
after sending in body "email" and "password" https://identitytoolkit.googleapis.com/ returns a few objects in the response.
One of them is "idToken": with a value of the token.
What do I need?
I need to get this token, store it in variable and reuse it in further tests.
So far I prepared something like this:
it("Get a fresh admin firebase token", () => {
cy.request({
method: "POST",
url: "https://identitytoolkit.googleapis.com/...",
body: {
"email": "myUsername",
"password": "myPassword",
"returnSecureToken": true
},
headers: {
accept: "application/json"
}
}).then((responseToLog) => {
cy.log(JSON.stringify(responseToLog.body))
}).then(($response) => {
expect($response.status).to.eq(200);
})
})
})```
Above code works, but cy.log() returns the whole body response. How can I separate only idToken and reuse it in my next API scenarios?
Considering that idToken in in response body so inside then() you can directly wrap the value and save it using an alias and then use it later.
it('Get a fresh admin firebase token', () => {
cy.request({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/...',
body: {
email: 'myUsername',
password: 'myPassword',
returnSecureToken: true,
},
headers: {
accept: 'application/json',
},
}).then((response) => {
cy.wrap(response.body.idToken).as('token')
})
})
cy.get('#token').then((token) => {
cy.log(token) //logs token or Do anything with token here
})
In case you want to use the token in a different it block you can:
describe('Test Suite', () => {
var token
it('Get a fresh admin firebase token', () => {
cy.request({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/...',
body: {
email: 'myUsername',
password: 'myPassword',
returnSecureToken: true,
},
headers: {
accept: 'application/json',
},
}).then((response) => {
token = response.body.idToken
})
})
it('Use the token here', () => {
cy.log(token) //prints token
//use token here
})
})
So I have a referer and Basic Auth that I need to send a Get Request, no body is needed. I am sending out the function like this, but I am getting a Failed to Fetch Error
fetch(myUrl, {
method: 'GET', // or 'PUT'
headers: {
'Referer': refererUrl,
},
authorization: {
'Authorization': 'Basic ' + btoa(authUser + ":" + authPassword),
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Referer is one of the headers that cannot be set by a client, for security reasons:
https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
So I able to successfully send a request via postman, but whenever I throw it into fetch I get back a 401 error.
export const createUser = () => {
return async (dispatch) => {
dispatch({ type: CREATE_USER });
console.log('we are in the create user function');
try {
let response = await fetch('secret.com/v1/login/signup', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: 'test1231273123#test.com',
password: 'Asadasd123123',
first_name: 'joe',
last_name: 'doe',
phone_number: '373738'
})
});
console.log('response ' + JSON.stringify(response));
} catch (error) {
console.log(error);
}
};
};
Here is the error I keep receiving.
response {"type":"default","status":401,"ok":false,"headers":{"map":{"access-control-allow-methods":["GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS"],"access-control-allow-origin":["*"],"connection":["keep-alive"],"access-control-allow-credentials":["true"],"content-length":["188"],"content-type":["text/html; charset=utf-8"],"access-control-allow-headers":["Content-Type, Accept, Authorization"],"www-authenticate":["Basic realm=\"Restricted\""],"date":["Thu, 12 Jan 2017 16:57:58 GMT"],"server":["nginx"]}},"url":"https://secret.com/v1/login/signup","_bodyInit":{},"_bodyBlob":{}}
My backend developer believes I ran into a cross domain issue and need to setup a proxy server? "set up some proxy server (I would recommend nginx) that would proxy ajax queries to our API domain"
I think it has something to do with fetch? Ideas?
I believe you need to provide the protocol, change:
await fetch('secret.com/v1/login/signup'...
to
await fetch('http://secret.com/v1/login/signup'