Axios - 使用 url + 变量发送 get 请求

时间:2021-06-01 22:49:11

标签: node.js axios

这一定是一个愚蠢的问题,但我才刚刚开始,希望得到任何帮助!

所以我有这个代码来获取查询参数:

app.get('/', (req, res) => {
var code = req.query.code;
console.log(code);

当我访问 http://localhost:3000/?code=123 时,我在控制台中获得了代码值,所以它工作正常。

现在,我需要发送一个 GET 请求并添加 var 代码的值,这就是我卡住的地方。 比方说,我应该向'http://testtesttest123.com/' + var code + 'hi' 发送一个 GET 请求。

我该怎么做?

我已经尝试过这种方式和其他一些方式,但没有任何效果:

 axios.get('http://testtesttest123.com/?&code=', {params: {code}}, '&hi')
.then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
});

先谢谢你!

2 个答案:

答案 0 :(得分:1)

axios.get 调用应如下所示。

axios.get('http://testtesttest123.com/?code=' + code + '&hi')

使用 code = 123,这将调用 URL http://testtesttest123.com/?code=123&hi

答案 1 :(得分:-1)

使用 params 配置通过查询参数发送。要支持您的空 hi 参数,您可以将其包含在 URL 字符串中

axios.get("http://testtesttest123.com/?hi", {
  params: { code }
})

对于 code123 值,这将执行 GET 请求以

http://testtesttest123.com/?hi&code=123

它还将确保 code 值在 URL 中的使用是安全的