数据返回的 Express Router Call 未定义

问题描述

我不断获取数据:未定义在我的 axios 调用中通过 nodemon 在 express 中调用我的路由。

axios({
                method: "POST",url:"http://localhost:8080/oracle2/search",headers: {"Content-Type" : "application/json;charset=utf-8"},data: {customer_number: values.custNumber.toString(),last_name: values.last_name}


            })
            .then(console.log('Axios Callback'))
          }

这是我的路由 oracle2:

router.post('/search',(req,res)=> {
    router.use(cors());
    router.use(bodyParser.json({ type: 'application/json' }))
    router.use(bodyParser.urlencoded({ extended: false,type: 'application/json' })) 

console.log(`The data: ${req.body}`)
res.sendStatus(200)

})

邮递员长这样:

标题

Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0
Accept: application/json,text/plain,*/*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip,deflate
Referer: http://localhost:3000/
Content-Type: application/json;charset=utf-8
Content-Length: 51
Origin: http://localhost:3000

身体看起来像这样:

{"customer_number":"120231546","last_name":"Smith"}

任何帮助将不胜感激。以 Formik 值作为输入响应前端

解决方法

这条路线不正确:

router.post('/search',(req,res)=> {
    router.use(cors());
    router.use(bodyParser.json({ type: 'application/json' }))
    router.use(bodyParser.urlencoded({ extended: false,type: 'application/json' })) 

    console.log(`The data: ${req.body}`)
    res.sendStatus(200)
});

这根本不是您使用中间件的方式。您没有在路由处理程序中定义 router.use() 语句。这将无法正常工作,并且每次运行路线时都会一遍又一遍地定义它们,从而导致它们永远堆积。通常,您可以通过以下方式在全球或跨多个路线应用此类中间件:

router.use(cors());
router.use(bodyParser.json({ type: 'application/json' }))
router.use(bodyParser.urlencoded({ extended: false,type: 'application/json' })) 

在任何路由处理程序之外,例如:

router.use(cors());
router.use(bodyParser.json({ type: 'application/json' }));
router.use(bodyParser.urlencoded({ extended: false,type: 'application/json'})); 

router.post('/search',res)=> {
    console.log('The data:',req.body);
    res.sendStatus(200);
});

或者,如果您真的希望中间件只对一条路由生效,那么您可以这样做:

router.post(
    '/search',bodyParser.json({ type: 'application/json' }),bodyParser.urlencoded({ extended: false,type: 'application/json'}),res)=> {
      console.log('The data:',req.body);
      res.sendStatus(200);    
});

请注意,我还更改了输出 req.body 内容的方式,因为它将是一个对象,并且实际上会在控制台中显示该对象的内容。