最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - HTTP status code 405 error when adding headers to request - Stack Overflow

programmeradmin4浏览0评论

I have a problem making get requests to a server when headers are being set with the Axios/http request. Any header I add (except the content-type header) causes the same error: "Response for preflight has invalid HTTP status code 405." This is true in Chrome, Firefox, Edge, etc.

Specifically, I need to add the Authorization header for account validation for a service I need to connect with.

Running a GET request on Postman using the API URI works fine and I get the required response. Running this in my React application in the browser gives me the HTTP 405 error. I'm running this on a local Node server with Google's Allow-Control-Origin extension installed and enabled using http://localhost:3000.

When I run the request without any header parameters:

axios.get(".svc/Login",).then(data => console.log(data)).catch(err => console.log(err))

The request works fine. When I run it with headers (any header, but in my case, the Authorization header), I get the error:

axios.get(".svc/Login", { headers: { "Authorization": "randomExample" } }).then(data => console.log(data)).catch(err => console.log(err))

So, what could be causing the issue? If it was a CORS or connection issue, wouldn't I have trouble making a request in general? I've been perusing Stack Overflow forever with no answer giving me the solution. I'm totally lost at what to do and I've been working on it for days already without a single solution. Any input would be much appreciated.

I have a problem making get requests to a server when headers are being set with the Axios/http request. Any header I add (except the content-type header) causes the same error: "Response for preflight has invalid HTTP status code 405." This is true in Chrome, Firefox, Edge, etc.

Specifically, I need to add the Authorization header for account validation for a service I need to connect with.

Running a GET request on Postman using the API URI works fine and I get the required response. Running this in my React application in the browser gives me the HTTP 405 error. I'm running this on a local Node server with Google's Allow-Control-Origin extension installed and enabled using http://localhost:3000.

When I run the request without any header parameters:

axios.get("https://myrequest./req/reqservice.svc/Login",).then(data => console.log(data)).catch(err => console.log(err))

The request works fine. When I run it with headers (any header, but in my case, the Authorization header), I get the error:

axios.get("https://myrequest./req/reqservice.svc/Login", { headers: { "Authorization": "randomExample" } }).then(data => console.log(data)).catch(err => console.log(err))

So, what could be causing the issue? If it was a CORS or connection issue, wouldn't I have trouble making a request in general? I've been perusing Stack Overflow forever with no answer giving me the solution. I'm totally lost at what to do and I've been working on it for days already without a single solution. Any input would be much appreciated.

Share Improve this question asked Mar 31, 2018 at 23:18 Mabeh Al-Zuq YadeekMabeh Al-Zuq Yadeek 844 gold badges18 silver badges31 bronze badges 9
  • Check this: stackoverflow./questions/48139612/… – user5734311 Commented Mar 31, 2018 at 23:25
  • Possible duplicate of 405 Method Not Allowed despite CORS – tanaydin Commented Mar 31, 2018 at 23:26
  • @tanaydin That question offers no solution to the problem. Am I missing something? – Mabeh Al-Zuq Yadeek Commented Mar 31, 2018 at 23:34
  • 405 - Method not allowed ... your server probably doesn't allow OPTIONS method - what is this "Google's allow-control-origin extension"? – Jaromanda X Commented Apr 1, 2018 at 0:34
  • @JaromandaX It's just a Chrome browser plugin that allows localhost munication between browser and server without causing CORS issues on localhost server. – Mabeh Al-Zuq Yadeek Commented Apr 1, 2018 at 18:21
 |  Show 4 more ments

3 Answers 3

Reset to default 9 +200

It is due to CORS. You need to specify the correct value for Access-Control-Allow-Headers server side for the preflight (OPTIONS) request (Documentation)

More details about CORS in general

Modify your server to add the missing header(s). From your question, you need to at least add Authorization value.

node js server

app.use(function (req, res, next) {
//...
res.setHeader('Access-Control-Allow-Headers', 'Authorization');

About Access-Control-Allow-Headers

The Access-Control-Allow-Headers response header is used in response to a preflight request to indicate which HTTP headers can be used during the actual request.

So, in your server side response, when setting Access-Control-Allow-Headers, you need to specify a list of ma-separated headers.

Access-Control-Allow-Headers: <header-name>, <header-name>, ...

You only need to specify it for custom headers, as by default some headers are already accepted.

The simple headers, Accept, Accept-Language, Content-Language, Content-Type (but only with a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain), are always available and don't need to be listed by this header.

So in your case it works if you just specify Content-type because Content-Type is accepted by default (as explained just above)

Note If the value for Content-type is not of one of the types above (e.g. if you submit your authorization request as application/json), then you need to add it in the list (ma-separated)

node js server

app.use(function (req, res, next) {
//...
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type');

If you want to make all routes cors enabled add the following script to your index.js.

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

If you want to make only a single route cors enabled you can enable it like this:

router.get('/corspage', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.send('cors problem fixed:)');
});

If you are OK with using additional package for that you can use cors package to do it with lot less code. Install the package and add the following code to index.js.

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

If you want to enable single route with cors package:

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

This error occurs because this is a CORS call and you get a preflight request to which your server must respond accordingly:

You will get an Origin: http://blah. header from the client.

There are several headers you should set when replying to preflight checks:

Access-Control-Allow-Origin: http://blah. - sets the allowed origins * - for all origins, or domain name if one is needed

Access-Control-Allow-Credentials: true - Set whether or not cookies are allowed from this origin.

Access-Control-Allow-Methods: POST, GET, OPTIONS - Actions allowed by this origin.

Access-Control-Allow-Headers: Content-Type - What headers are allowed from this origin you may set custom headers here.

These preflight checks are OPTIONS calls not GET or POST so you can easily detect them and answer correctly. You may not answer content to the Options call but only set these mandatory headers so the client knows what the CORS policy for this connection is. After this has been done the client will issue the actual GET/POST request as you have issued it in the ajax calling the server.

发布评论

评论列表(0)

  1. 暂无评论