I want to change an API call (external source, no chance to change something on the API side) from PHP to Javascript (Learning purposes).
Because of the cross-origin, I use fetch(). When I run my script, I get an Unexpected end of input error and can't figure out why.
function postData(url = '', data = {}) {
var headers = new Headers();
headers.set('Authorization', 'Basic ' + window.btoa("user" + ':' + "pass"));
return fetch(url, {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(data),
}).then(response => response.json()).catch(error => console.error(error));
}
postData('https://www.api-endpoint.com/cat1/api/search?', {
"searchID": "710",
"isTagged": true
}).then(data => console.log(JSON.stringify(data))).catch(error => console.error(error));
How can I identify the problem with this code? It seems the Authorization is okay. I implemented the search parameters (searchID and isTagged) as described on the manual from the API Dev.
Thanks in advance!
You said mode: 'no-cors', which disables everything which requires CORS permission.
Since reading data across origins requires CORS permission, there is no data.
Trying to parse an empty string as JSON results in the unexpected end of input because the input ended before there was any JSON.
(Note that other things which require CORS permissions, and which you are trying to do, include setting the content-type to JSON and including credentials).
Related
I am trying out the new Fetch API but is having trouble with Cookies. Specifically, after a successful login, there is a Cookie header in future requests, but Fetch seems to ignore that headers, and all my requests made with Fetch is unauthorized.
Is it because Fetch is still not ready or Fetch does not work with Cookies?
I build my app with Webpack. I also use Fetch in React Native, which does not have the same issue.
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
In addition to #Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include' for the first /api/auth call too.
If you are reading this in 2019, credentials: "same-origin" is the default value.
fetch(url).then
Programmatically overwriting Cookie header in browser side won't work.
In fetch documentation, Note that some names are forbidden. is mentioned. And Cookie happens to be one of the forbidden header names, which cannot be modified programmatically. Take the following code for example:
Executed in the Chrome DevTools console of page https://httpbin.org/, Cookie: 'xxx=yyy' will be ignored, and the browser will always send the value of document.cookie as the cookie if there is one.
If executed on a different origin, no cookie is sent.
fetch('https://httpbin.org/cookies', {
headers: {
Cookie: 'xxx=yyy'
}
}).then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
P.S. You can create a sample cookie foo=bar by opening https://httpbin.org/cookies/set/foo/bar in the chrome browser.
See Forbidden header name for details.
Just adding to the correct answers here for .net webapi2 users.
If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.
// Access-Control-Allow-Origin
// https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
My issue was my cookie was set on a specific URL path (e.g., /auth), but I was fetching to a different path. I needed to set my cookie's path to /.
If it still doesn't work for you after fixing the credentials.
I also was using the :
credentials: "same-origin"
and it used to work, then it didn't anymore suddenly, after digging much I realized that I had change my website url to http://192.168.1.100 to test it in LAN, and that was the url which was being used to send the request, even though I was on http://localhost:3000.
So in conclusion, be sure that the domain of the page matches the domain of the fetch url.
I am trying out the new Fetch API but is having trouble with Cookies. Specifically, after a successful login, there is a Cookie header in future requests, but Fetch seems to ignore that headers, and all my requests made with Fetch is unauthorized.
Is it because Fetch is still not ready or Fetch does not work with Cookies?
I build my app with Webpack. I also use Fetch in React Native, which does not have the same issue.
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
In addition to #Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include' for the first /api/auth call too.
If you are reading this in 2019, credentials: "same-origin" is the default value.
fetch(url).then
Programmatically overwriting Cookie header in browser side won't work.
In fetch documentation, Note that some names are forbidden. is mentioned. And Cookie happens to be one of the forbidden header names, which cannot be modified programmatically. Take the following code for example:
Executed in the Chrome DevTools console of page https://httpbin.org/, Cookie: 'xxx=yyy' will be ignored, and the browser will always send the value of document.cookie as the cookie if there is one.
If executed on a different origin, no cookie is sent.
fetch('https://httpbin.org/cookies', {
headers: {
Cookie: 'xxx=yyy'
}
}).then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
P.S. You can create a sample cookie foo=bar by opening https://httpbin.org/cookies/set/foo/bar in the chrome browser.
See Forbidden header name for details.
Just adding to the correct answers here for .net webapi2 users.
If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.
// Access-Control-Allow-Origin
// https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
My issue was my cookie was set on a specific URL path (e.g., /auth), but I was fetching to a different path. I needed to set my cookie's path to /.
If it still doesn't work for you after fixing the credentials.
I also was using the :
credentials: "same-origin"
and it used to work, then it didn't anymore suddenly, after digging much I realized that I had change my website url to http://192.168.1.100 to test it in LAN, and that was the url which was being used to send the request, even though I was on http://localhost:3000.
So in conclusion, be sure that the domain of the page matches the domain of the fetch url.
I am trying out the new Fetch API but is having trouble with Cookies. Specifically, after a successful login, there is a Cookie header in future requests, but Fetch seems to ignore that headers, and all my requests made with Fetch is unauthorized.
Is it because Fetch is still not ready or Fetch does not work with Cookies?
I build my app with Webpack. I also use Fetch in React Native, which does not have the same issue.
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
In addition to #Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
Have just solved. Just two f. days of brutforce
For me the secret was in following:
I called POST /api/auth and see that cookies were successfully received.
Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, because of no cookies were sent with the request.
The KEY is to set credentials: 'include' for the first /api/auth call too.
If you are reading this in 2019, credentials: "same-origin" is the default value.
fetch(url).then
Programmatically overwriting Cookie header in browser side won't work.
In fetch documentation, Note that some names are forbidden. is mentioned. And Cookie happens to be one of the forbidden header names, which cannot be modified programmatically. Take the following code for example:
Executed in the Chrome DevTools console of page https://httpbin.org/, Cookie: 'xxx=yyy' will be ignored, and the browser will always send the value of document.cookie as the cookie if there is one.
If executed on a different origin, no cookie is sent.
fetch('https://httpbin.org/cookies', {
headers: {
Cookie: 'xxx=yyy'
}
}).then(response => response.json())
.then(data => console.log(JSON.stringify(data, null, 2)));
P.S. You can create a sample cookie foo=bar by opening https://httpbin.org/cookies/set/foo/bar in the chrome browser.
See Forbidden header name for details.
Just adding to the correct answers here for .net webapi2 users.
If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.
// Access-Control-Allow-Origin
// https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
This works for me:
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function headers(set_cookie=false) {
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}
Then build your call:
export function fetchTests(user_id) {
return function (dispatch) {
let data = {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
body: JSON.stringify({
user_id: user_id
}),
headers: headers(true)
};
return fetch('/api/v1/tests/listing/', data)
.then(response => response.json())
.then(json => dispatch(receiveTests(json)));
};
}
My issue was my cookie was set on a specific URL path (e.g., /auth), but I was fetching to a different path. I needed to set my cookie's path to /.
If it still doesn't work for you after fixing the credentials.
I also was using the :
credentials: "same-origin"
and it used to work, then it didn't anymore suddenly, after digging much I realized that I had change my website url to http://192.168.1.100 to test it in LAN, and that was the url which was being used to send the request, even though I was on http://localhost:3000.
So in conclusion, be sure that the domain of the page matches the domain of the fetch url.
There is such a vue method:
methods: {
sendTrackerClientData () {
return axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id=00227220201402050613" , {
tracking_data: 'some data'
})
.then(response => {
console.log('post method is working!');
})
.catch(function (error) {
console.log(error);
});
},
}
Which is hung on a button click event
After trying to send data, we can see the warnings and error described above in the firebug.
Trying to add headers by type:
return axios.post("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking.data_save&key_id="+ this.$store.state.tracker.trackingKeyId , {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
})
.then(response => {
console.log('post method is working!');
})
.catch(function (error) {
console.log(error);
});
It didn’t lead to anything.
Question:
How can I solve this problem?
OK, let's break this down:
axios.post("... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId , {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
})
The first argument you're passing to post is the URL. I'm going to assume that's the correct URL.
The second argument you're passing is this object:
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'X-Powered-By': 'bacon'
},
tracking_data: this.$store.state.tracker.trackingClientData
}
This is wrong in multiple ways.
Firstly, you seem to be trying to add response headers as request headers. Neither Access-Control-Allow-Origin nor X-Powered-By should be there. They should be on the server.
But they aren't actually being set anyway because you've put the headers config in the wrong place. The arguments for post should be url, data, config. The headers need to go in the config, not the data.
axios will set the content-type header automatically. In the case of your request it'll set it to application/json. However, that will trigger a CORS preflight OPTIONS request as it isn't one of the 3 safe-listed content-types.
I don't know what content-type the API you're using expects but if you need to avoid the preflight request then you'll need to set it to one of application/x-www-form-urlencoded, multipart/form-data or text/plain. e.g.:
axios.post("... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId , {
tracking_data: this.$store.state.tracker.trackingClientData
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
However, the data is still being encoded as JSON here (so the content-type header and the request body don't actually match). I believe jQuery defaults to encoding the data as a URL encoded query string. The official axios documentation for doing that is here:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
However, all of this very much depends on exactly what format the server is expecting.
As you only have a single parameter it might be possible to do something like this:
axios.post(
"... lots of stuff ..."+ this.$store.state.tracker.trackingKeyId,
'tracking_data=' + encodeURIComponent(this.$store.state.tracker.trackingClientData),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
)
To debug this further you should carefully inspect the headers being sent each way in the Network tab of your browser's developer tools. Make sure they are exactly what you're expecting. There shouldn't be any mysteries here, you can see exactly what headers are being used.
Further, if you aren't clear on how CORS works and what can trigger a preflight OPTIONS request then you should do some background reading on that.
Finally, you need to find out exactly what format your server is expecting for the data. We can speculate all day about what the correct code might be but if we know what we're aiming for then there's no need to guess.
I would add that the jQuery example you posted has tracking_data spelt incorrectly as traking_data. That won't be related to the CORS error but it makes me wonder whether it really 'works'.
The issue means server restricts cross-origin requests. Those headers you've tried to add should be added on the server side. There is no way you can make it work without modifying your server code/settings.
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
I'm trying to get service API data with authorization headers, but getting 401 - Unauthorized error and the response is Missing Request Headers.
Tried with sending authorization content with body also - getting same error 401 - Unauthorized error.
Edited:
headers: {
'userName': "xyz",
'sessionToken': "xyz................."
}
When I'm checking with Postman client it is working fine, but not with the redux-saga fetch method. Kindly help me for this.
Looks like it's a backend problem - CORS Filter configuration
If the backend is on a different server (could be on the same machine, but in a different Application Server, in other words, on a different port) you have to do some CORS Filters configurations.
The frontend code is running on a server - that means it's an application. Postman is a client, just like Google Chrome or any other browser. That's the explanation why you can do the request without any problem from Postman but unsuccessful from your frontend application.
I guess you enabled the Access-Control-Allow-Origin header on the backend
Now you have to allow your custom headers with Access-Control-Allow-Headers
Whenever I use fetch and I need to add headers to the request I do it this way:
headers: new Headers({
Accept: 'application/json',
Authorization: token,
'Content-Type': 'application/json',
}),
so you might want to try this approach, also in order to debug this issue you might want to check your Netowrk tab and verify which headers are sent with the request.
You need to add an Authorization bearer header.
For instance:
headers = new Headers({
'Authorization': `Bearer ${authorizationCodeOrCredentials}`
});
In your code:
return fetch(`{SERVICE API URL}`, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + someValue, // Add this line
'userName': "username",
'password': "password",
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(json => dispatch(receivePosts(reddit, json)))
If you are using Linux system & If you have chrome in it...
Run your chrome using following command
/opt/google/chrome/chrome --disable-web-security --user-data-dir
Try now, If everything works fine then it's CORS issue from Backend.