在React和Express中处理查询



在我的React应用程序中的某个地方,我使用REST API向服务器发送请求。在我的URL中,我想使用查询(在postIconsTransition method中(,但当我向服务器发送请求时,服务器告诉我找不到这个URL(我在服务器中生成了这个错误(。如果我在没有任何查询的情况下使用此URL,则postIconsTransition method中的请求可以正常工作。postIdauthContext.userId工作正常,有人能告诉我我的代码出了什么问题吗?

在我发送请求的组件中:

const likeHandler = async () => {
setLike(prevState => !prevState);
if (!like) {
try {
await postIconsTransition(props.postId, "inc");
} catch (error) {}
} else {
try {
await postIconsTransition(props.postId, "dec");
} catch (error) {}
}
};

useHttp.js组件中:

const postIconsTransition = async (postId, addtionAddress) => {
return await transitionData(
`http://localhost:5000/post/${postId}/${authContext.userId}?t=${addtionAddress}`,
"POST",
null,
{ Authorization: `Bearer ${authContext.token}` }
);
};

transitionData方法:

const transitionData = useCallback(
async (url, method = "GET", body = null, headers = {}) => {
setIsLoading(true);
const abortController = new AbortController();
activeHttpRequest.current.push(abortController);
try {
const response = await fetch(url, {
method,
body,
headers,
signal: abortController.signal
});
const responseData = await response.json();
activeHttpRequest.current = activeHttpRequest.current.filter(
reqCtrl => reqCtrl !== abortController
);
if (!response.ok) {
throw new Error(responseData.message);
}
setIsLoading(false);
return responseData;
} catch (error) {
modalContext.err(error);
setIsLoading(false);
throw error;
}
},
[modalContext.err]
);

快递:

router.post(
"/:postId/:userId?t=inc",
tokenChecker,
postController.updateLikesComments
);
router.post(
"/:postId/:userId?t=dec",
tokenChecker,
postController.updateLikesComments
);

所有这些都可以正常工作,但当我在URL中使用查询时,它就不再工作了。

您不会在这样的快速路由中指定查询参数。只需发送即可。Express可以读取。

router.post(
"/:postId/:userId",
tokenChecker,
postController.updateLikesComments
);
// Notice that you don't need the other one.

在控制器中检查参数

// controller's code
const t = req.query.t;
if (t === 'inc') {
// do what you want here
}
if (t === 'dec') {
// do what you want here
}

最新更新