繁体   English   中英

无法从 Node.js 服务器请求中获取参数 Axios

[英]Not able to get params from Node.js Server Request by Axios

我正在尝试制作一个尝试发送短信的简单应用程序。 我正在使用 Axios 向服务器发送请求以发送 SMS,并且我正在使用 Node.js 作为服务器。

下面给出的是 App.js 向服务器发送请求的代码片段,参数 NUM 包含 twilio(短信服务)必须向其发送短信的号码

const sendSMSClinic = async () => {
  console.log("CLINIC SMS SENDING FUNCTION ACCESSED");
  try {
    let res = await axios.get("http://localhost:3001/api/mail", {params: {
      NUM: "971561490375"
    }});
  } catch(AxiosError) {
    console.log(AxiosError)
  }
}

下面给出的是 index.js 的代码,它启动 node.js 服务器并尝试发送短信

const express = require('express');
const app = express();
const port = process.env.PORT || 3001;

var cors = require('cors')

app.use(cors())

const accountSid = 'AC8ae163a17e6e3d2ce63e64a98bac68c4'; 
const authToken = '0a13cc33147e4ffb34682097fbf6c49d'; 
const client = require('twilio')(accountSid, authToken); 

app.get('/api/mail/:NUM', async (req, res) => {
    console.log(req.params.NUM);

    client.messages 
        .create({         
            to: '+971561490375',
            from: '+16188160866',
            body: 'REASON FOR CALL: CLINIC EMERGENCY'
        }) 
        .then(message => console.log(message.sid)) 
        .done();
})

app.get("/",(req,res)=>{
    res.status(200).send("successful")
})

app.listen(port, () => {
 console.log('Server is up and running on port ', port);
})

问题是我收到以下错误

GET http://localhost:3001/api/mail?NUM=971561490375 404 (Not Found)

AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

您应该将您的axios请求更改为:

const num = "971561490375";
const res = await axios.get(`http://localhost:3001/api/mail/${num}`)

如果要添加多个路径参数,可以将端点声明编辑为:

app.get('/api/mail/:NUM/:NUM2', (req, res) => {
    console.log(req.params.NUM, req.params.NUM2);
    ...
}

您的axios请求:

const num = "971561490375";
const num2 = "971561490375";
const res = await axios.get(`http://localhost:3001/api/mail/${num}/${num2}`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM