如何获取axios的重定向响应?

uin*_*nct 1 javascript node.js express reactjs axios

我认为该请求没有问题,因为我使用了相同的请求来发布新角色并且成功了。我认为问题出在回应上。

后端使用 Express 和 Node

我有一个更新角色的API 路线。

router.put('/:id', (req, res, next) => {
    const { id } = req.params;
    Promise.all([
        updateAbilities(id, req.body.abilities, next),
        updateCharacter(id, req.body.name, req.body.img, next),
        updateShows(id, req.body.shows, next)
    ])
        .then(values => console.log(values, 'are the values received at put request'))
        .then(() => res.redirect('/' + id))
        .catch(err => next(err));
})
Run Code Online (Sandbox Code Playgroud)

当我使用Postman发送请求时,我得到了完美的响应。

邮递员回复的图像

使用 Axios 在 React 应用程序中进行前端

我正在使用Axios在 React 应用程序上执行相同的请求。

export async function updateOne(inputs, cid) {
    inputs = {
        name: "green latern 2",
        abilities: "ring, superpower",
        shows: "justice league",
        img: "an image",
    };
    cid = 11;
    let err = null
    const response = await axios({
        method: 'PUT',
        url: BASE_URL + cid,
        data: inputs
    }).catch(e => err = e);

    console.log(response, 'was the response');
    return;
}
Run Code Online (Sandbox Code Playgroud)

但这样做时,我收到此错误:

Error: Network Error
    createError createError.js:16
    handleError xhr.js:83
    dispatchXhrRequest xhr.js:80
    xhrAdapter xhr.js:12
    dispatchRequest dispatchRequest.js:52
    promise callback*request Axios.js:61
    wrap bind.js:9
    updateOne apiCalls.js:36
    js apiCalls.js:66
    Webpack 22
 was the response apiCalls.js:42
Run Code Online (Sandbox Code Playgroud)

代码可以在 GitHub 上找到:https://github.com/uinstinct/card_builder

如果您需要更多信息,我会提供您需要的信息。请评论相同

uin*_*nct 7

在浏览了类似问题的几乎所有搜索结果后,我发现了这些:

  • 来自重定向 url(由后端本身重定向)的数据无法由任何库处理 - 无论是 axios、fetch 还是 XMLHttpRequest 本身

这种情况不会发生,因为后端应用程序(在本例中为:express)发送res.status.code302信息基本上告诉浏览器:“您正在查找的数据无法在此 url 中找到,但在我将您重定向到的 url 中找不到”

此代码根本无法在任何库中工作:

app.get("/i/came/here",function(req,res){
 return res.redirect("/now/go/here"); // the actual data stored here
}
Run Code Online (Sandbox Code Playgroud)

您甚至可能会收到 CORS 错误

  • 如果您尝试重定向到 url,则可能无法使用 axios 或 fetch,除非您使用拦截器或其他类型的中间件或函数来处理句柄错误。

是的,每当后端尝试产生重定向时,axios 总会抛出错误

更多相关信息: https: //github.com/axios/axios/issues/932#issuecomment-307390761

  • 当您尝试这样做时,没有办法(我发现)可以从 url 获取重定向数据 axios 将始终抛出错误。最好的解决方案(我发现)是在后端应用程序本身中处理结果数据。

对于这个问题中处理的特定问题,我更改了更新字符的后端路由,如下所示:

router.put('/:id', (req, res, next) => {
    const { id } = req.params;
    Promise.all([
        updateAbilities(id, req.body.abilities, next),
        updateCharacter(id, req.body.name, req.body.img, next),
        updateShows(id, req.body.shows, next)
    ])
        .then(values => console.log(values, 'are the values received at put request'))
        .then(() => getOneById(id,res))
        .catch(err => next(err));
})
Run Code Online (Sandbox Code Playgroud)

我使用了一个名为 的函数getOneById(id,res),它处理获取特定字符并发送 json 响应的逻辑。

我欢迎所有的编辑和建议。如果我错了,请纠正。 请在下面留下相同的评论