【问题标题】:How to get the redirected response from axios?如何从 axios 获取重定向响应?
【发布时间】:2020-12-13 21:18:01
【问题描述】:

我认为请求没有问题,因为我使用了相同的请求发布新角色并且它成功了。 我认为问题在于响应

使用 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));
})

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

Image of postman response

使用 Axios 的 React App 前端

我正在使用 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;
}

但是这样做时,我收到了这个错误:

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

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

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

【问题讨论】:

  • 你能在网络标签中查看吗? api是否命中?
  • BASE_URL 的值是多少,也在邮递员中发送 x-www-form-urlencoded 但在您的代码中它是一个普通的 js 对象。
  • @Reyno BASE_URL 的值是 http://localhost:9000/ 并且工作正常

标签: javascript node.js reactjs express axios


【解决方案1】:

在浏览了这个类似问题的几乎所有搜索结果之后,我想出了这些:

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

这不可能发生,因为后端应用程序(在这种情况下:快递)发送302res.status.code 基本上告诉浏览器:“您正在寻找的数据不能在此 url 中找到,但在 url 中我将您重定向到"

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

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

您甚至可能会遇到 CORS 错误

  • 如果您尝试重定向到某个 url,那么这甚至可能不适用于 axios 或 fetch,除非您使用 interceptor 或其他类型的中间件或函数来处理句柄错误。

是的,只要后端尝试产生重定向,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));
})

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

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

【讨论】:

    【解决方案2】:

    您的 Postman 请求使用了 x-www-form-urlencoded,您需要将您的 inputs 对象转换为 url 编码字符串。

    还将 axios 内容类型标头更改为 x-www-form-urlencoded,因为默认情况下它是 application/json

    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
    

    const inputs = {
      name: "green latern 2",
      abilities: "ring, superpower",
      shows: "justice league",
      img: "an image",
    };
    
    
    const urlencoded = Object.entries(inputs).map(([key, value]) => {
      return encodeURIComponent(key) + "=" + encodeURIComponent(value);
    }).join("&");
    
    console.log(urlencoded);

    【讨论】:

    • 我真的不认为这是 json 或 url 编码的问题,因为我的发布路线完全正常。 pastebin.com/0Nv8GE0d我尝试了其他方法,现在得到了这个错误:pasteboard.co/JnYB6N9.png
    • @uinstinct 您的 CORS 设置中似乎有错误。您的服务器需要输出以下标头:Access-Control-Allow-Origin: http://localhost:9000
    • @uinstinct 此外,PUT 请求和 x-www-form-urlencoded 不会触发设置 CORS 标头的 OPTIONS 调用。 More info here。尝试添加 morgan 中间件以查看是否正在进行 OPTIONS 调用。 app.use(morgan("dev"))
    • 我认为服务器本身没有问题,我认为问题在于axios,因为数据库中的字符已更新。这意味着请求成功但没有响应。你可以自己看看here
    【解决方案3】:

    在 Postman 中,您将数据发送为 x-www-form-urlencoded。 Axios 可能会将您的数据以 JSON 格式发送,其中 content-typeapplication/json。您的 Express App 是否能够处理 json 请求?您需要使用 bodyParser 中间件:

    通过 npm: npm i body-parser

    在你的应用中,你需要 require 它然后使用中间件:

    const bodyParser = require('body-parser');
    // ...
    // ...
    app.use(bodyParser.json());
    

    编辑:正如 cmets 中所指出的,您还可以使用 express.json() 中间件,这是相同的。

    app.use(express.json());

    ...没有任何安装。

    【讨论】:

    • Express 内置了body-parser,无需安装。只需使用express.json()
    • 我不认为这是 body-parser 的问题,因为我的 post route 已经在工作了此外,我已经使用了 body-parser const bodyParser = require('body-parser'); const cors = require('cors'); const routes = require('./routes'); const app = express(); app.use(cors()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多