All my GET requests are going through but POST ones fail. This happens when I update fetch-mock from 7.3.0 to 7.3.1 or later.
console.warn Unmatched POST to url
Error fetch-mock: No fallback response defined for POST to url
http.js
export const get = (url) => {
const options = {
method: 'GET',
credentials: 'same-origin'
};
return fetch(url, options).then(handleJsonResponse);
};
export const post = (url, body) => {
const headers = {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
};
return fetch(url, {
credentials: 'same-origin',
method: 'POST',
cache: 'no-cache',
body: JSON.stringify(body),
headers
}).then(handleJsonResponse);
};
http.spec.js
const url = '/path/to/url'
describe('get', () => {
it('makes a GET request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'GET',
credentials: 'same-origin',
response: {
status: 200,
body: []
}
});
const response = await get(url);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(response).toEqual([]);
});
});
describe('post', () => {
const requestBody = {request: 'request'};
it('makes a POST request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'POST',
credentials: 'same-origin',
cache: 'no-cache',
body: JSON.stringify(requestBody),
headers: {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
},
response: {
status: 200,
body: []
}
});
const response = await post(url, requestBody);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(fetchMock.lastOptions().headers).toEqual({
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
});
expect(response).toEqual([]);
});
});
Any thoughts on what's causing this? Is there a way to get more meaningful logs to help with debugging this?
I would rather not go the alternative path of trying nock or jest-fetch-mock.
Alright, after hours of digging into the library itself I have found out where the issue was.
In my code (and the snippet above) I am stringifying the body JSON.stringify(body). The library's generate-matcher.js is parsing it JSON.parse(body) and then compares the two - the point which was causing the failure. I am now just sending it as the raw object.
In case anyone else ends up here in the future, I had the same error accompanied with fetch-mock unmatched get.
I saw the response to this issue filed to fetch-mock which prompted me to double check my expected values and mocked values.
It turns out my problem was exactly as the error described, where the mock route I was expecting and the actual route that was being called were mismatched because of a typo.
Related
I am trying to add couple of image attachments in google api, I am not able to find any kind of solution for it, though I am able to send mail without it, can any one help on adding attachments.
const encodedMail = btoa([
`From: ${guest_email}\r\n`,
`To: ${toHotel}\r\n`,
`Subject: ${fullname} Sent Mail\r\n\r\n`,
`Hello There\n\n I have Just Mailed, Please find my details\n\n Name: ${fullname}\n
Phone: ${phone}\n `
].join('')).replace(/\+/g, '-').replace(/\//g, '_');
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify({
'raw': encodedMail
})
});
if (response) {
console.log(response)
}
Help would be really appreciated.
how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})
I have this REST request that I can't seem to get to work correctly.
This is just the "login" to the resource but I assume the same problem will occur as I move forward.
var bodyinfo = {
ApiKey: "#theapikey",
Username: "#theusername",
Password: "#thepassword" };
fetch('{base-url}/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(bodyinfo)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I've tried to stringify the headers as well but I always end up getting 'Status Code: 415 Unsupported Media Type'.
The HTTPRequest works fine when testing with either Postman or when I run it through a HTTPRequest in WebStorm.
I've got a Relay setup from howtographql tutorial:
const network = Network.create((operation, variables) => {
// 4
return fetch(GRAPHQL_URL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'same-origin', // <- added it to enable cookies, but it's a probably a default option anyway
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json();
});
});
I want Relay to attach a cookie to its request but it doesn't work even when I added credentials: 'same-origin'. Here's the similar issue on GitHub (even though it's more about the auth component, so this question should have a simple solution).
I'm need send user data at request to my endpoint (rest api), but gets 401 error only if make request from the js side. If make request from Postman, I get 200 status. I did everything as in the documentation. for reference: make request from Nodejs. Thanks
var token = 'Token 897d3c9991952bc715fcf6c3e262e5b3866342';
var myHeaders = new Headers();
myHeaders.append('Authorization', token);
fetch(this.domain + '/v1.0/user/data/', {method: 'GET', headers: myHeaders, mode: 'no-cors'})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('error');
}
})
Check this link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch or you can use axios to make request.
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('http://<host>:<port>/<end-point>?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
fetch:
// Example POST method implementation:
postData(`http://<host>:<port>/<end-point>`, {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error));
function postData(url = ``, data = {}) {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, same-origin, *omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}