【问题标题】:Send post request with Axios with body and headers使用带有正文和标头的 Axios 发送 post 请求
【发布时间】:2021-08-13 08:00:24
【问题描述】:

我正在做一个项目,我需要使用 bitly 为链接创建一个短 URL。 我通过使用Nodejs的请求包获得了成功。 这是我到目前为止所做的。

const token = process.env.BITLY_ACCESS_TOKEN;
    let headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    };
    var dataString = `{ "long_url": "${req.body.url}"}`;
    const api_url = "https://api-ssl.bitly.com/v4/shorten";
    var options = {
      url: api_url,
      method: "POST",
      headers: headers,
      body: dataString,
    };

    request(options, (error, body) => {
      if (error) {
        return res.status(404).send(error);
      }
      return res.render("index", { error: "", data: JSON.parse(body.body) });
    });

我的问题是我们如何使用 Axios 而不是请求包,因为请求包已被弃用。

我尝试了但没有成功。

const token = process.env.BITLY_ACCESS_TOKEN;
    let headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    };
    var dataString = `{ "long_url": "${req.body.url}"}`;
    const api_url = "https://api-ssl.bitly.com/v4/shorten";

    const response = await axios.post(
      api_url,
      { long_url: req.body.url },
      {
        headers: headers,
      }
    );
    return res.render("index", { error: "", data: response });

我收到错误,例如未定义正文。 请帮我。谢谢!

【问题讨论】:

  • 能否显示错误回溯
  • 感谢您的快速回复。我得到了解决方案。比你。

标签: node.js axios request url-shortener bitly


【解决方案1】:
const response = await axios.post(api_url, dataString, {
  headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 2019-05-27
    • 2020-12-23
    • 1970-01-01
    • 2018-12-06
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    相关资源
    最近更新 更多