So I have a test like this. My problem is that the app does not get populated with this data even though I can see the correct data when I log the response. What am I doing wrong?
test('should show name', async ({ page }) => {
page.on('response', (response) => {
console.log(response.json().then((d) => console.log(d)));
});
await page.route('**/**', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: '[{"id":1,"name":"John"}]',
})
);
await page.goto('http://localhost:4200/names');
await expect(page.locator('[data-test=name]')).toHaveText('John');
});
Related
I've created a new Zapier integration and it works okay so far. But when I turn of the Zap created using the integration, the unsubscribe webhook doesn't get called. For testing, I've used https://webhook.site as the unsubscribe url but it never gets called. Here's the code that shows in the unsubscribe code mode:
const options = {
url: 'https://webhook.site/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-KEY': bundle.authData.key
},
params: {
},
body: {
'hookUrl': bundle.subscribeData.id,
'key': bundle.authData.key
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = response.json;
// You can do any parsing you need for results here before returning them
return results;
});
I'm trying to take info from a React form and post it to my Rails database, but I get an error "unexpected token '<' at position 0" which means my response is still HTML and not JSON.
Here's my code:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => response.json())
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
}
Is there a reason why it's not converting to JSON?
Additionally, I don't seem to be able to drop debugger into my code, or at least in this function - do I need to import it or something?
I'm thinking that your server is sending you back HTML and then you are trying to parse it in response.json()
use a try/catch in this block:
export const createCar = car => {
return dispatch => {
return fetch(`${API_URL}/cars/create`, {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ car: car })
})
.then(response => {
try {
return response.json()
} catch(error) {
console.error(error);
}
})
.then(car => {
dispatch(addCar(car))
dispatch(resetCarForm())
})
.catch(error => console.log(error + 'createCar POST failed'))
}
newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.
I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?
I'm struggling with this strange problem, I can't seem to solve. I'm using isomorphic fetch to to post data to a server. I'm sending the body as a JSON-string. But on the server, I can't read the body, it's just an empty object.
The stack is: node, react.
Here is the client-code:
handleSubmit = (event) => {
const { dispatch } = this.props;
fetch('/api/me', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'xxx'
})
})
.then(response => response.json())
.then( json => dispatch( login( json ) ))
.catch( err => console.log(err) )
}
The server code:
var jsonParser = bodyParser.json()
app.post( '/api/me', jsonParser, ( req, res ) => {
console.log('req', req.body);
})
I've tried googling the problem. But the few solutions I found, didn't to the trick.
All help is much appreciated.
BR
Martin
// UPDATE //
figured it out, it was a silly 's', I had forgotten. 'header' should be 'headers'
Thank you for the update that one of the params should be plural:
headers: {
'Accept': ...,
'Content-Type': ...
},
You appended it to the question. Please feel free to accept this as the answer, or to create a new answer with that text, and accept it. Then the "unanswered" queue will contain one less dangling entry for folks to stumble upon.