Express Router Call返回的数据未定义



我的axios通过nodemon调用我的express路由时一直得到data: undefined

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"}

任何帮助都会很感激。React前端使用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', (req, 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'}),
(req, res)=> {
console.log('The data:', req.body);
res.sendStatus(200);    
});

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

最新更新