I need to set up a cookie in browser after sending a POST request in a javascript(js) and try to ask the browser to send this new-set cookie back in a subsequent fetch GET request.
Here is my js script:
fetch(authorise_url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify({
"code": code
})
}).then((response) => {
const url_test = 'http://localhost:8888/test-cookie/';
return fetch(url_test, {credentials: 'include'})
.then((response) => {
console.log(response.text());
}).then((error) => {
console.log(error);
})
});
Server side code in authorise_url:
response.set_cookie('test_cookie', 'test_cookie_value', httponly=True)
Server side code in test-cookie:
print(str(request.COOKIES))
I read Fetch API with Cookie and used credentials: 'include' in my JS requests. Cookie is set up in browser but the cookie is not sent but my subsequent GET request.
I tested sending two GET requests, the cookie can be set up and sent by send GET fetch request using the following code.
function getCookie() {
fetch(authorise_url, {
credentials: 'include'
}).then((response) => {
console.log(response.text());
const url_test = 'http://localhost:8888/test-cookie/';
return fetch(url_test, {credentials: 'include'})
.then((response) => {
console.log(response.text());
}).then((error) => {
console.log(error);
})
});
}
But I failed to get the cookie in the combination of POST and GET fetch request.
Is there some considerations when sending the GET request with cookie after a POST?
Related
I have the following problem. I have a server who implemented his own authentication process. For that they take the credentials as body.
async function authenticate(){
var cred = JSON.stringify({
"email": "user#test.de",
"password": "1234"
});
const response = await fetch("http://.../rest/auth/login", {
method: 'POST',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: cred
})
}
The response has the code 200 and says "login successfull!" and has a SET-COOKIE header has
the session cookie.
Now I've a second request with which I load the actual data. But when I try this and I get the response code 401: Unauthorized.
async function getData(){
const now = new Date()
const response = await fetch(`http://.../rest/....`)
console.log(response)
const data = await JSON.parse(response)
console.log(data)
}
authenticate()
.then((res) => {
console.log(res)
getData().then(reso => console.log(reso))
})
Im not sure how to handle this problem.
I've already checked all responses and everything worked except that the second request doesnt use the Cookie in their request. I've also tried to use the WithCredentials=true option but without success.
EDIT
I changed the credentials from
credentials: 'cross-origin' -> credentials: 'include'
Since im calling an extern Server from localhost.
But i get still an 401 Error.
I am sending a GET request to an API.
The browser must send a cookie and an API Key on the fetch request.
The problem that I face is the following:
If I send the request without the API Key on header, the cookie is sent on the request:
fetch(urlToRequest, {
method: "GET",
mode: "cors",
credentials: "include"
})
.then((response) => {
console.log(response);
})
.catch ((error) => {
console.log(error)
});
If I include the Header with API Key, the cookie is not send on the request:
fetch(urlToRequest, {
method: "GET",
mode: "cors",
credentials: "include",
headers: {"api-key": apiKey}
})
.then((response) => {
console.log(response);
})
.catch ((error) => {
console.log(error)
});
Is this behave normal? Shouldn't the browser send the cookie and the api key aswell?
it's a Chrome problem,in some cases Chrome debugger do not show the cookie. The cookie has been sent i think.
I want to send data to my sever but I got this error:
TypeError: Failed to fetch
my codes:
function login(username, password) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json','charset':'utf-8' },
body: JSON.stringify({ 'username':username , 'password':password })
};
console.log(requestOptions);
return fetch(BASE_URL+serverConstants.LOGIN_POST_REQUEST, requestOptions)
.then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
})
.then(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
}
return user;
});
}
but I tested it on postman I got correct response.
Your preflight request is failing. Allow cross origin for the API you are hitting:
In node you do it like this,
res.header("Access-Control-Allow-Origin", "*");
Hope this helps
If you want to send values to your sever like form-data from postman sowftware you should use formData (your don't need to import FormData from any class):
var formData = new FormData()
formData.append('yourKey, 'yourValue');
var requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: formData
};
return fetch('Your url', options)
.then(checkStatus)
.then(parseJSON);
of course from your server-side you should enable CORS. CORS depending on your language server-side is different.
I have a rest api endpoint and I am checking it using POSTMAN which is posting correctly. But, when I am doing it using JAVASCRIPT FETCH, I am not able to post it. Below is my code for fetch:
const { inputAOI, wktForCreation } = this.state
fetch('http://192.168.1.127:8080/aoi/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ userName: 'fuseim', aoiName: inputAOI, wkt: wktForCreation }),
mode: 'no-cors'
}).then(function (response) {
if (response.ok) {
return response.json()
} else {
throw new Error('Could not reach the API: ' + response.statusText)
}
}).then(function (data) {
console.log({ data })
}).catch(function (error) {
console.log({ error })
})
Below is the image for the request headers.
It is seen in the above image that in Request Headers, the Content-Type is still text/plain but I am sending application/json as shown in above fetch code.
Check the response preview in console.
Below is correct POSTMAN request:
As hinted in the comments, the problem is with the mode:"no-cors"
Content-Type is considered a simple header, and should be allowed without cors, but only with the following values:
application/x-www-form-urlencoded
multipart/form-data
text/plain
See: https://fetch.spec.whatwg.org/#simple-header
If you are running the API on the same host/port as the script, you should use mode: "same-origin" alternatively add the host/port that the script is running on as an allowed origin on the API.
For more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Instead of
headers: {
'Content-Type': 'application/json'
}
you could try:
headers: new Headers({
'Content-Type': 'application/json'
})
in my React app, I have the following API POST to allow the user to edit their profile (name and image).
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
The problem with the above is the header with the Authorization token is not being sent in the POST...
How can I get the Authorization header to be send in the fetch request above?
FYI, for non-multipart forms, the authorization token is sent successfully like so:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
You can’t use no-cors mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
To append a name/value pair to a Headers object (headers), run these steps:
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.
In that algorithm, return equates to “return without adding that header to the Headers object”.
Authorization isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use no-cors mode for a request. Same for Content-Type: application/json.
If the reason you’re trying to use no-cors mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, no-cors mode isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
By using below code you can make a fetch request with Authorization or bearer
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));