如何从URL提取ISBN参数以正确构造书评POST请求的前端问题
问题排查&修复方案
1. ISBN提取逻辑错误
你当前使用window.location.search提取ISBN,这个API只能拿到URL中?后的查询参数,但你的页面路径是/review/${ISBN编号},ISBN属于路径参数而非查询参数,所以无法拿到正确值。
正确提取方式是拆分路径window.location.pathname,取最后一段作为ISBN。
2. fetch请求路径错误
你写的api/review/${isbn}是相对路径,会自动拼接当前页面路径前缀,实际请求路径会变成/review/xxx/api/review/xxx,和后端路由不匹配,需要在路径开头加/指定为根路径。
3. 表单提交事件绑定错误
你把submit事件绑定在了类为.form-group的div元素上,submit事件只能在<form>标签上触发,导致提交逻辑根本不会执行。你页面里的表单id是blog-form,直接绑定这个元素即可。
修复后的前端JS代码
const newFormHandler = async (event) => { event.preventDefault(); const description = document.querySelector('#description').value.trim(); const reviewTitle = document.querySelector('#reviewTitle').value.trim(); // 拆分路径取最后一段作为ISBN const pathSegments = window.location.pathname.split('/'); const isbn = pathSegments[pathSegments.length - 1]; if (description && reviewTitle && isbn) { const response = await fetch(`/api/review/${isbn}`, { method: 'POST', body: JSON.stringify({ description, reviewTitle }), headers: { 'Content-Type': 'application/json', }, }); if (response.ok) { document.location.reload(); } else { const err = await response.text(); console.error('请求错误详情:', err); alert('Failed to create review'); } } }; // 绑定到form元素本身 document .querySelector('#blog-form') .addEventListener('submit', newFormHandler);
验证步骤
- 打开页面控制台,刷新后确认没有JS报错
- 提交表单时查看控制台Network标签,确认请求路径、请求体参数是否符合预期
- 如果还有错误可以查看后端接口返回的具体报错信息进一步排查
内容的提问来源于stack exchange,提问作者hannahatl
相关产品推荐
相关产品推荐

