I have the following codes:
save: {
method: 'POST',
headers: {
'X-L5S-View-Mode': 'front',
'Content-Type': 'application/json',
'Accept-Language': ''
},
transformRequest: function (data, getHeaders) {
console.log(resource.lang);
var headers = getHeaders();
headers['Accept-Language'] = resource.lang;
console.log(headers);
return JSON.stringify(data);
}
}
in my resource factory.
Weirdly, all my headers are converted to lower case.
Here's the log:
fr <-- resource.lang
Object {x-l5s-view-mode: "front", content-type: "application/json", accept-language: "", accept: "application/json, text/plain, */*", Accept-Language: "fr"…} <-- headers
Why are my headers in lower case?
Plus, when I inspect with Chrome, I found that the Accept-Language is blank. So even I have changed the Accept-Language with headers['Accept-Language'] = resource.lang;, it doesn't work at all.
Because the latest version of Angular do not support this way to modify the headers anymore.
Angular 1.3.20 works for me.
Just change the version of Angular in bower.json, delete the original Angular, then cd to your directory and run bower install.
Related
I am trying to pass a bearer token, to the fastify http server, in my headers.
I set the headers inside my request as:
...
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
}
const token = localStorage.getItem('token')
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
const newOptions = {
...options,
mode: 'no-cors',
headers
}
console.log('options:', newOptions)
return fetch(url, newOptions)
My console.log prints:
options: {
mode: "no-cors",
headers: {
Accept: "application/json",
Content-Type: "application/json",
Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
}
}
From the Chrome network tab, I look at the headers, and Authorization is just not present there. My route handler function is below:
async function user(server, options) {
server.route({
method: 'GET',
url: '/user/:email',
handler: async (req, res) => {
const username = req.params.email
console.log('user email:', username)
console.log('headers:', req.headers)
res.send({
type: 'promoter'
})
}
})
}
When I print headers on the server, it also does not have Authorization, showing:
headers: { host: 'localhost:5000',
connection: 'keep-alive',
pragma: 'no-cache',
'cache-control': 'no-cache',
accept: 'application/json',
'sec-fetch-dest': 'empty',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'no-cors',
referer: 'http://localhost:3000/admin',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-US,en;q=0.9,ru;q=0.8' }
What am I missing?
Another interesting issue is that when I run the request from Postman it shows 200 response code, and fastify prints 200 to the log. However, running from the saga/request with:
return fetch(url, newOptions)
.then(checkStatus)
.then(parseJSON)
I get response.status of 0 instead of 200 inside the request method, while the server log still shows "res":{"statusCode":200}.
I figured out what was the problem.
Apparently, my version of Chrome - Version 80.0.3987.106 (Official Build) (64-bit) and possibly other browsers and older versions of Chrome, as well, strip the authorization header, when it is used in conjunction with the no-cors mode. Enabling CORS and setting the appropriate headers solves the problem.
Try adding withCredentials: true and credentials: 'include' to your options:
options: {
mode: "no-cors",
withCredentials: true, // <-- ADD THIS
credentials: 'include', // <-- AND THIS
headers: {
Accept: "application/json",
Content-Type: "application/json",
Authorization: "Bearer NQ9xQLmYtq92aT8JHHRd7DGZJ..."
}
}
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
I have a problem, I'm trying to access an API via javascript fetch().
In their documentation, they only have the curl guide
curl https://test.com/form/{form_id}/data \
-u apikey:'some-key'
Can you guys help me convert it to javascript fetch?
I tested the code below but the browser console says error 401 now I don't think I did put the apikey on the right location.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
apikey : 'some-ley',
'Content-Type': 'application/json'
}
})
Thanks in advance. :)
I think what is failing there is the type of header you are sending in fetch.
The -u option in curl translates to the "authorization" header in fetch. So it would be something like this.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'authorization' : 'Basic apikey:some-key',
'Content-Type': 'application/json'
}
})
Although probably you would need to base64 encode the apikey:some-key portion before sending it.
Try this format:
fetch("https://test.com/form/{form_id}/data", {
headers: {
Authorization: "apikey ABCDEFGHIJK.."
}
})
Try these awesome online cURL converters!
Here is the output when you paste the cURL command and select the Javascript target:
fetch('https://test.com/form/371489/data', {
headers: {
'Authorization': 'Basic ' + btoa('apikey:some-key')
}
});
i want to force the content-type to application/json but i have a mode "no-cors" and actually the return for content-type is : text/plain;charset=UTF-8 its the same when i pass the headers so i don't know how do this.
I have already tried to use fetch or Axios, the URL is in HTTP and i work in local so maybe it's the problem?
I have tried on Postman, that work great.
fetch('http://link', {
method: 'POST',
credentials: 'include',
redirect: 'follow',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"cluster_id" : [],
"surname" :["albert"],
"gender" :[],
}),
}).then((result) => {
this.setState({ allClient: result.data }, () => {
this.setState({ load: true })
console.log(this.state.allClient)
})
So, i want to have content type: application/json and not Content-Type: text/plain;charset=UTF-8
You've mentioned CORS and localhost, but I don't know that your issue is with either of them based on the information provided.
The content-type header specifies the MIME type for the body following the header. For your request, it's the type of the request body. For the response, it's the type for the response body.
You're correctly setting the content type of your request, and telling the server what you're looking for w/ the accept header, but ultimately it's up to the server-side to set the header. If you control the server, you can adjust as needed, but otherwise you're stuck consuming what is being served.
Can't send authorization header with rest API. Got 'OPTIONS' error with status 0. All headers and options are allowed on the server. Server is written on PHP.
Here is my request:
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData},{
headers:{ 'Content-Type':'multipart/form-data',
Authorization:`Bearer ${token}`}
})
It seems like it does not send the header when there is authorization. However, it works, if i delete authorization, and leave only content type
This should do the trick
axios({
method: 'POST',
url:`${API_URL}users/${23}/profile/main/update`,
headers: {
'Content-Type':'multipart/form-data',
'Authorization':`Bearer ${token}`},
data: formData
})
Refer docs for browser
Try to send as below:
var headers = {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${token}`
}
axios.post(`${API_URL}users/${23}/profile/main/update`,
{formData}, headers)
Try using Ajax call below:
import $ from 'jquery';
$.ajax({
url:`${API_URL}users/${23}/profile/main/update`,
processData: false,
contentType: false,
data : formData,
method : "POST",
headers: {
"Authorization": `Bearer ${token}`
}
});
I had this same issue, it is possible that you are not passing the sent auth header from your apache config to your php application.
you might need to set
WSGIPassAuthorization On
inside your virtualhost config.
Check this
I made API server with DRF so if delete the data, I have to use DELETE method.
So I tried to request to server with method: 'DELETE', But it doesn't work.
[js file]
fetch("http://abc/article/24",
{
method: "DELETE",
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: JSON.stringify({password: '123'})
})
I captured packet with Chrome Network tab, It's Request Header is OPTION.
In my code, I defined method to DELETE. But why Request Header's METHOD is OPTION?
[ADDED SCREENSHOT]
I set the response code if success, return 204, fail return 304
[SOLVED]
Solved by Content-Type: 'application/json' and payload into http body.
That works perfectly.