无法使用axios进行post请求,返回未经授权的401错误

问题描述 投票:0回答:3

我使用 Redux、React 和 Node 从头开始创建了一个身份验证服务。一切都工作正常,直到我将 Post 部分或 redux 连接到后端。我想 redux 部分还可以。我的问题是当我发送授权承载令牌时。我可以用失眠来发帖。但当我尝试使用网络应用程序发帖时,我却做不到。 这就是我的行动:

export const createPost = ( formValues: any) => async(dispatch: any, getState: any) => {
  const { userId } = getState().auth;
  let token = userId

  const headers = {
    header: {
      'Content-Type' : 'application/json',
      'Accept' : 'application/json',
      Authorization: `Bearer ${token}`
    }
  };
  const response = await AlleSys.post('/posts', {...formValues, headers})
  // dispatch({type: CREATE_POST, payload: response.data})

userId 是我的 JWT 令牌。

我已经在我的后端设置了 Cors

const corsOptions ={
    origin:'http://localhost:3000',
    credentials:true,            //access-control-allow-credentials:true
    optionSuccessStatus:200
}
app.use(cors(corsOptions))

关于失眠。对失眠的同样要求效果很好。

在失眠时,我使用应用程序中相同的不记名令牌,因此问题不在于 JWT。

redux axios
3个回答
0
投票

从 Nodejs 服务器或 Insomnia 使用 GET、POST、PUT、DELETE 查询端点将导致在检查选项之前进行调用。

但是浏览器会限制 HTTP 请求位于同一域,这会让您遇到 CORS 问题。由于 Insomnia 不是浏览器,而 CORS 只是浏览器安全限制,因此它没有受到限制。

来自您正在使用的 CORS 的 docs

某些 CORS 请求被认为是“复杂”的,并且需要初始 OPTIONS 请求(称为“飞行前请求”)。 “复杂”CORS 请求的一个示例是使用 GET/HEAD/POST 之外的 HTTP 动词(例如 DELETE)或使用自定义标头的请求。要启用飞行前功能,您必须为要支持的航线添加新的 OPTIONS 处理程序:

所以我认为你应该在所有路由之前包含 app.options('*', cors()) 并将其放在文件的顶部首先进行处理。


0
投票

我将代码更改为:

export const createPost = ( formValues: any) => async(dispatch: any, getState: any) => {
  const { userId } = getState().auth;
  let token = userId

  const headers = {
    authorization: `Bearer ${token}`
  };
  const response = await AlleSys.post('/posts', {...formValues}, {headers})

并且成功了!


0
投票

对于 DELETE 请求,请确保添加

data
headers
配置。请参阅下面的示例:

await axios.delete(`${serverURL}/locations/delete`, {
  data: {
    foo: "bar,
  },
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${authToken}`,
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.