Request header field <field-name> is not allowed by Access-Control-Allow-Headers in preflight response

社会主义新天地 提交于 2021-02-15 04:55:46

问题


I have a React app that is trying to make an axios request to my Express server to find a user in a Mongo database. Before, I built the back-end on Rails and had a gem for CORS, and after trying to configure CORS on the Express side, I can't seem to find a solution. I want to be able to pass in a custom field in headers (i.e. username) so I can use that field to query against my database.

Error I get in browser:

XMLHttpRequest cannot load http://localhost:3000/api/users/test. 
Request header field username is not allowed by Access-Control-Allow-Headers 
in preflight response.

My Express server has the following CORS set up and my React axios code is attempting to make a request to the server with a param passed into the headers objects, but still getting preflight in response error.

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
  res.setHeader("Access-Control-Allow-Headers",
    "Access-Control-Allow-Headers, 
    Origin, 
    Accept, 
    X-Requested-With, 
    Content-Type, 
    Access-Control-Request-Method, 
    Access-Control-Request-Headers, 
    Authorization")
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

export const loadAccount = (username) => {
  return(dispatch) => {
    axios
    .get(`${url}/users/test`, {
      headers: {username: username}
    })
    .then(resp => {
      dispatch({
        type: 'LOAD_ACCOUNT',
        account: resp.data
      })
    })
    .catch(errors => {
      console.log(errors)
    })
  }
}

回答1:


Seems to me like you have to add username as a valid header in your Access-Control-Allow-Headers clause, i.e.:

res.setHeader("Access-Control-Allow-Headers",
  "Access-Control-Allow-Headers, 
  Origin, 
  Accept, 
  X-Requested-With, 
  Content-Type, 
  Access-Control-Request-Method, 
  Access-Control-Request-Headers, 
  Authorization,
  username")
res.setHeader('Cache-Control', 'no-cache');
next();


来源:https://stackoverflow.com/questions/44250594/request-header-field-field-name-is-not-allowed-by-access-control-allow-headers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!