When i create header object and pass it , it is not working, it is not even hitting the server
const post = async (url, request) => {
let testHeader = new Headers();
testHeader.append('Accept', 'application/json');
testHeader.append('Content-Type', 'application/json');
const response = await fetch(url,
{
method: 'POST',
credentials: 'same-origin',
headers: testHeader,
body: JSON.stringify(request)
}
);
return responseHandler(request, response);
};
but when i pass the headers like this , it works with out any issues
const post = async (url, request) => {
const response = await fetch(url,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
}
);
return responseHandler(request, response);
};
Related
Using axios I want to send a request with X-Auth-Token in header.
Which one is the correct solution for doing this:
const url = `https:/.../${sku_id}/tokens/${token}`;
const result = await axios.post(url, { headers: { 'X-Auth-Token': token } });
Or this one:
const result = await axios.post(url, { headers: { 'Authorization': `token ${token}` } });
I have a problem in fetch data ?
in my header , i will send token for authentication to my back-end but i don't know how i can add header to get method ..
fetch('https://api.github.com/users/mralexgray/repos', {
method: 'GET',
header: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Aequseted-With": "XMLHttpRequest",
"Authorization": `Bearer ${token}`
}
}).then((result) => {
result.json()
console.log(result)
if (result.status == 200) {
async function GetLink() {
const response = await fetch('https://api.github.com/users/mralexgray/repos')
const data = await response.json();
console.log(data)
sessionStorage.setItem('userAttemps', data[0].id);
sessionStorage.setItem('freeAttemps', data[0].id);
}
GetLink()
}
}).catch(err => {
console.error(err);
});
userAttemps = sessionStorage.getItem('userAttemps')
freeAttemps = sessionStorage.getItem('freeAttemps')
Is my code correct?
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await 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'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
I want to get data from the URL I have entered as req.body.url inside the body of postman collection tool
how do I get the response
I have a key as URL and the value as live URL see the below screenshot
const options = {
url: req.body.url,
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
request(options, function(err, res, body) {
let json = JSON.parse(options);
res.send(json);
console.log(json);
});
tried above code but it does reads the URL and does not provide the data as response
use this :
var request = require('request');
const options = {
url: req.body.url,
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Note that request is asynchronous
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,
})
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.