【问题标题】:Send params from frontend to be used in a NodeJS Get request从前端发送参数以在 NodeJS Get 请求中使用
【发布时间】:2021-12-07 08:13:42
【问题描述】:

我正在尝试将数据传递到我的 Node.js 后端,以便在对 API 的获取请求中使用它。

例如:

Server.js

const PORT = 8000
const axios = require('axios').default
const express = require('express')
const app = express()
const cors = require('cors')
app.use(cors())
require('dotenv').config()
app.use(express.json())

app.get('/convertedAmount', (req, res) => {
  const contentBody = req.body

  const options = {
    method: 'GET',
    url: 'https://currency-converter5.p.rapidapi.com/currency/convert',
    params: {format: 'json', from: contentBody.primaryCurrency, to: 
    contentBody.secondaryCurrency, amount: contentBody.primaryCurrencyAmount},
    headers: {
      'x-rapidapi-host': process.env.RAPIDAPI_HOST,
      'x-rapidapi-key': process.env.RAPIDAPI_KEY,
    },
  }

  axios
    .request(options)
    .then((response) => {
      res.json(response.data)
    })
    .catch((error) => {
      console.error(error)
    })
})

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))

问题是,我不知道如何将数据从前端传递到后端,而不是使其成为 POST 请求。但是,如果我向 rapidAPI url 发出 POST 请求,这将不起作用。所以后端需要保持不变。

我的问题是,我将如何为此编写前端部分?

在前端使用 POST 请求将数据与 req.body 一起发送,但我无法让数据显示在浏览器的 localhost:8000/convertedAmount 上。

谢谢

我的尝试是:

Frontend.js
...

  axios.post('/convertedAmount', {
    primaryCurrency: 'USD',
    secondaryCurrency: 'GBP',
    primaryCurrencyAmount: 1
  })
  .then((response) => {
    console.log(response);
  }, (error) => {
    console.log(error);
  })

...

【问题讨论】:

  • 我想你正在寻找这个。 See

标签: node.js express http post


【解决方案1】:

您不应该尝试通过 GET 请求在正文中(例如在 req.body 中)发送数据。这就是 POST 请求的用途。

对于 GET 请求,您应该将数据(例如用户 ID)作为参数传递。基本上,在 url 字符串中。

前端

axios.get("/convertedAmount/USD/GBP/1")

后台

app.get("/convertedAmount/:primaryCurrency/:secondaryCurrency/:primaryCurrencyAmount", (req, res)=>{
    console.log(req.params.primaryCurrency);
    console.log(req.params.secondaryCurrency);
    console.log(req.params.primaryCurrencyAmount);
});

或者,您可以使用查询字符串,如下所示:

前端

axios.get("/convertedAmount?primaryCurrency=USD&secondaryCurrency=GBP&primaryCurrencyAmount=1")

后台

app.get("/convertedAmount*", (req, res)=>{
    console.log(req.query.primaryCurrency);
    console.log(req.query.secondaryCurrency);
    console.log(req.query.primaryCurrencyAmount);
});

【讨论】:

    猜你喜欢
    • 2016-10-21
    • 2018-04-23
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多