Send cookie and API Key on the fetch request - javascript

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.

Related

Javascript: multiple fetches

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.

net::ERR_CERT_AUTHORITY_INVALID with JavaScript fetch request on new Microsoft Edge

Having an issue when trying to perform a fetch request.
fetch("https://localhost:5001/api/Blog/", {
method: "GET",
mode: "no-cors",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
credentials: "include"
}).then(response => {
console.log(response);
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
This is my request I'm sending and here is the error I'm getting.
GET https://localhost:5001/api/Blog/ net::ERR_CERT_AUTHORITY_INVALID
Anyone know how I can get around this error.
Note:
I have tested the request on 2 other computers and this worked fine.
By changing my GET request to mode: "cors" and also trusting my API in trusted root authorities. I was able to send a request to the API. Unsure why this is but it was my solution.

Axios not showing headers in xhr browser

I added a Authentication header in my axios request but when I show the response header in browser in XHR, I cannot see the header I set. Thats why the api response telling me Please login first. Did i miss something? thanks for answering
What I tried is
getMerchants(){
this.$axios.get(`/userCoins/getMerchantLists?limit=10&offset=1`,null,{
headers: {
'Authentication': this.$cookies.get('auth_token'),
}
}).then((res)=>{
this.merchants = res.data.results
console.log(this.$cookies.get('auth_token'))
console.log(res.data)
}).catch((err)=>{
this.$toast.global.error_toast()
})
},
In the console, What i get is
1000028:a3bb0cb30689cd8bdaee8bf09e1c5e277341526383be8ff7f78e49223144d05baa056d00
{status: "Please login first"}
The first is my cookie and the second is the api response.
Here is my browser request headers
Try using axios like this:
const req = {
url: '/userCoins/getMerchantLists?limit=10&offset=1',
method: 'GET',
headers: { Authorization: this.$cookies.get('auth_token') }
}
return this.$axios(req)

Sending Cookie back with a fetch(GET) after a fetch(POST) request

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?

javascript fetch is not posting to rest api endpoint while postman is doing

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'
})

Categories