使用带有正文和标题的 Axios 发送 post 请求

时间:2021-05-25 04:31:09

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

我正在开发一个项目,我需要使用 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 });

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

1 个答案:

答案 0 :(得分:1)

const response = await axios.post(api_url, dataString, {
  headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });