无法在标头请求上设置授权?

时间:2018-03-05 21:36:00

标签: javascript cors fetch

我的快递服务器上已有此代码:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Authorization");
  next();
});
app.use('/graphql', graphqlExpress(async(req) => {
  let {user} = await getUser(req.headers.authorization);
  return ({
    schema,
    pretty: true,
    graphiql: true,
    context: {
      user
    }
  })
}))

我认为这是cors问题所以我在本教程中使用了express-cors for express:https://enable-cors.org/server_expressjs.html

此代码是我处理提取的方式:

let token = localStorage.getItem('token');
const fetchQuery = (operation, variables) => {
  return fetch('/graphql', {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': token,
    },
    body: JSON.stringify({query: operation.text, variables})
  }).then(response => {
    // A better error message for request timeouts
    if (response.status === 504) {
      return Promise.reject({
        error: {
          message: 'Request timed out'
        }
      })
    }
    return response.json()
  }).then(responseJson => {
    // https://github.com/facebook/relay/issues/1816
    // https://github.com/facebook/relay/issues/1913
    if (responseJson.errors) {
      return Promise.reject(responseJson.errors[0])
    }
    return Promise.resolve(responseJson)
  })
}

但是,即使用户登录后已有令牌,发送给服务器的授权也始终为空?

1 个答案:

答案 0 :(得分:0)

localStorage.getItem("token")未执行,可能是由于getItem是I / O操作,以及导出的工作原理。将其移到fetchQuery

const fetchQuery = (operation, variables) => {
  const token = localStorage.getItem("token");
  return fetch('/graphql', {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': token,
    },
    body: JSON.stringify({query: operation.text, variables})
  }).then(response => {
    // A better error message for request timeouts
    if (response.status === 504) {
      return Promise.reject({
        error: {
          message: 'Request timed out'
        }
      })
    }
    return response.json()
  }).then(responseJson => {
    // https://github.com/facebook/relay/issues/1816
    // https://github.com/facebook/relay/issues/1913
    if (responseJson.errors) {
      return Promise.reject(responseJson.errors[0])
    }
    return Promise.resolve(responseJson)
  })
}