前端的 Axios.post 不返回 ant 结果



这个应用程序的想法是,用户在网站主页的搜索栏输入Twitter帐户id(比如'nodejs'),并使用axios。将其发布到服务器。Express应用程序使用该字符串从Twitter API提取数据。

我可以获得在运行Express的控制台上显示的API结果,但我无法将结果返回给客户端。它只是不返回任何东西。对于网站的URL,它应该是localhost:3000/dashboard/nodejs,但它最终与localhost:3000/?search=nodejs(输入元素的名称是'search')。然后网站就不会切换,停留在主页上。

fetchTweets(客户端):

const fetchTweets = (value, postBody) => {
console.log('fetched from frontend')
return (
axios.post(`/${value}`, postBody)
.then(res => {
const result = res.data;
return { result }
})
)
}

handleSubmit(调用fetchTweets):

const handleSubmit = async (value) => {
try {
const postBody = { twitterId: '0' }
const res = await fetchTweets(value, postBody);
console.log(res)
if (res.result.usernameError) {
setError('No username found. Please enter a correct username')
console.log(error)
}
else if (res.result.serverError) {
setError('Error Fetching Data from Server')
console.log(error)
}
else {
setTweets(res.result)
history.push({
pathname: `/dashboard/${value}`,
})
}
} catch {
setError('Error fetching data from server.')
}
}

搜索组件:

<Search 
onSubmit={async (value) => {
setError(false);
setLoading(true);
handleSubmit(value)
}} />

路由器(服务器):

router.post('/:account', async function (req, res, next) {
try {
lastTwitterId = req.body.twitterId;
twitterObject = await twitter.getTweets(req.params.account.toLowerCase(), lastTwitterId);
res.status(200).json(twitterObject)
res.status(200).end();
} catch {
res.status(501).json({ serverError: true })
}
});

这里的问题是fetchTweets()没有等待axios请求。它不返回任何东西,因为当您返回时请求仍在进行中。

同时,try-catch优于.then().catch()

的例子:

const fetchTweets = (value, postBody) => {
console.log('fetched from frontend');
try {
const response = await axios.post(`/${value}`, postBody);
return response.data;
} catch(err) {
return err.message;
}
}