Multiple headers in REST call giving #415 error - javascript

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.

Related

using http with axios return 400 with request it works

I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.

fetch-mock: No fallback response defined for POST

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.

issue with reading result from POST in fetch request to Github API

I am using the fetch api to get an access token returned from the github api.
When I check the network tab I see that the token is returned but I am unable to access it in my fetch request.
My code looks like this:
fetch(`https://github.com/login/oauth/access_token?client_id=***&client_secret=***&code=${code}&redirect_uri=http://localhost:3000/&state=react`, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
}).then(function(res) {
console.log(res); // I have already tried return res.json() here
})
The console displays the following error if I return res.json():
index.js:30 Uncaught (in promise) SyntaxError: Unexpected end of input
The GitHub docs states the response takes the following format:
By default, the response takes the following form:
access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer
I guess it isn't returning valid json but just a string so I am not sure how to access this response.
The response looks like this:
However, when I try and log out the response I get SyntaxError: Unexpected end of input
If you are using mode: 'no-cors, browser will restrict to access body. Browser has security for cross domain. If you want to access body you have to call without mode: 'no-cors property.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
This will work
fetch(`https://jsonplaceholder.typicode.com/posts/1`, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
.then(function(res) {
console.log(res);
})
This will not work
fetch(`https://jsonplaceholder.typicode.com/posts/1`, {
method: 'GET',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(res => res.json())
.then(function(res) {
console.log(res);
})
I think you're almost there. You've mentioned this link to the docs. If you read further, you can see that to get response in JSON, you need to include a header named Accept with the value of application/json.
fetch(` ... `, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
}).then(function(res) {
...
})
This way, you can apply .json() on res.

Fetch response malformed

The issue is basically that the fetch response object is not correct. Pictures to clarify the issue are below as it is hard to explain.
My fetch request code.
fetch(this.constructUrl(url), {
method: method,
mode: 'no-cors',
headers: new Headers({
'Authorization': 'Bearer ' + this.token,
'Accept': 'application/json',
'Content-Type': 'application/json',
}),
body: new FormData(document.getElementById(formIdentifier))
}).then(function (response) {
if (response.ok) {
return response.json().then(callback);
}
console.log(response);
}).catch(function(error) {
console.log(error);
});
The fetch response object.
The chrome response/request details
The chrome response data
So as you can see, the data in chrome looks correct but for some reason, the fetch response object does not seem to reflect what chrome picks up.
I had to switch 'no-cors' to 'cors' and allow cors in my rest stack.

React Native Fetch Request Fails Without CSRF Token

I've been developing a mobile complement to my web application built with Rails. Using Fetch API, I keep getting the notice "Can't verify CSRF token authenticity".
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({user})
})
// promise handling
}
Edit: Managed to get it to work but I still don't really understand why. If anyone has the same problem, this is how I resolved it. I managed to get the form_authenticity_token from my rails application and saved it as a variable that I then passed to the function. Haven't tested removing the credentials key.
export const login = (user, token) => {
return fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ user, authenticity_token: token })
})
You need to add CSRF token in headers or disable / remove CSRF on cross domain request.
export const login = (user) => {
fetch('http://localhost:3000/api/session', {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
},
body: JSON.stringify({user})
})
// promise handling
}
When working with Django backend you should set:
'X-CSRFToken': csrf_token // not 'X-CSRF-Token' !!!
in your JS request headers.
Environment:
To set the token on the backend side, use:
{% csrf_token %} <!-- put this in your html template -->
And then, to get the token in the JS code:
const csrf_token = document.getElementsByName('csrfmiddlewaretoken')[0].value;

Categories

Resources