带有参数的Axios Node.Js GET请求未定义

时间:2019-09-30 21:45:32

标签: node.js reactjs axios

我正在后端运行带有nodejs的React应用。每当我进行不带参数的axios调用时,一切正常,但是当我尝试添加参数并将其与req.body.variableName一起使用时,它将输出未定义的内容。打印req.body只是一个空的花括号,因此不发送我的数据。

与axios调用反应文件

getFriendCount(){
    var data = {
        UserID: this.state.UserID,
    }
    console.log(data)
    axios.get("http://localhost:8081/getFriendCount", data).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })
}

serversql.js

const HTTP_PORT = process.env.PORT || 8081;
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
const cors = require("cors");
const mysql = require('mysql');

app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const {addNewMemory,getAllMemories, getFriendCount} = require('./db-services.js');

//Database connection...

app.get('/data', getAllMemories);
app.post('/addMemory',urlencodedParser,addNewMemory);
app.get('/getFriendCount',urlencodedParser, getFriendCount);

app.listen(HTTP_PORT, ()=>{console.log("API listening on: " + HTTP_PORT)});

db-services.js(未定义req.body.UserID)

module.exports={
  getFriendCount:(req,res) => {
    console.log(req.body)        //empty curly brace
    console.log(req.body.UserID) //undefined
    console.log(req.params)      //empty curly brace
    var sql = "SELECT COUNT(*) AS friendCount FROM friendship WHERE UserId1 = (?) OR UserId2 = (?)";
    var values = [req.body.UserID, req.body.UserID]
    dbconnection.query(sql, values, function(err,result,fields){
        if(err){
            return res.status(500).send(err);
        } else {
            res.send(result);
        }
    })
},
}

3 个答案:

答案 0 :(得分:1)

Axios.get()中,数据表示参数,而不是主体数据。 因此,请使用req.params代替正文。 然后,节点以这种方式使用路由。

app.get('/getFriendCount/:Id',urlencodedParser, getFriendCount);

然后请使用下面的ID。

console.log(req.params.Id);

然后您需要像这样更改API。

axios.get(`http://localhost:8081/getFriendCount/${this.state.UserID}`)

请尝试这个。

答案 1 :(得分:0)

如果要发送body,则不能使用GET方法。在这种情况下,仅应使用POST或PUT方法。 GET方法仅采用paramquery,其中`params可以这样使用:

app.get('/getFriendCount/:id', handler);

如果您致电/getFriendCount/123,则req.param.id将返回123

query可以这样使用:

/getFriendCount?name=pedro-请求查询将产生{ name:"pedro" }

答案 2 :(得分:0)

在客户端尝试以下操作

  axios.get("http://localhost:8081/getFriendCount", {
          params: {
            UserID: yourUserID
          }
        }).then((response)=>{
        if (response.status >= 400) {
            console.log(response.status);
            throw new Error("Bad response from server");
        } else{
            return response.data[0].friendCount
        }
    }).then((data)=>{
        console.log(data)
        this.setState({count: data})
    })

,并且在服务器端使用body代替query,就像这样console.log(req.query.UserID)。希望这会有所帮助:)

相关问题