我使用 React 并尝试发帖。 我收到的错误是 SyntaxError: Unexpected token '<', "
如果我这次删除那行代码,我会得到一个 500 内部服务器错误 响应 {type: 'cors', url: 'http://localhost:3000/api/post/', redirected: false, status: 500, ok: false, …} 身体 : 可读流 车身二手 : 错误的 标题 : 标题 {} 好的 : 错误的 重定向 : 错误的 地位 : 500 状态文本 : “内部服务器错误” 类型 : “科尔斯” 网址 : “http://localhost:3000/api/post/” [[原型]] : 回应
我的身体在 ReadableStream 中,错误可能在这里,但是当我检查我的代码时,我在发送之前进行了字符串化。所以我很困惑。
const handleSubmit = async (e) => {
e.preventDefault();
// Récupérer les données du formulaire
const title = e.target.title.value;
const description = e.target.description.value;
const data = { title, description };
try {
// Envoyer les données au backend avec la méthode POST
const url = "http://localhost:3000/api/post/";
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.getItem("token"),
// authorization doit ettre ds headers
},
body: JSON.stringify(data),
// Authorization: `Bearer ${authCtx.token}`
});
const json = await response.json();
// Vérifier si la requête a été traitée avec succès
if (response.ok) {
// Fermer la fenêtre modale
console.log(json);
console.log("response ok");
handleCloseModal();
// Actualiser la page pour afficher le nouveau post
window.location.reload();
} else {
console.log(response);
}
} catch (error) {
console.log(error);
if (error.response && error.response.status === 401) {
console.log("Erreur 401 : authentification requise");
}
}
};
return (
<div>
<Button onClickProps={handleOpenModal}>Creer un post</Button>
<Modal isOpen={modalIsOpen} onRequestClose={handleCloseModal}>
<form className="form-post" onSubmit={handleSubmit}>
<h2>Ajouter un nouveau post</h2>
<div>
<label htmlFor="title">Titre</label>
<input type="text" id="title" onChange={(e) => console.log(e)} />
</div>
<div>
<label htmlFor="description">Description</label>
<textarea id="description"></textarea>
</div>
<button type="submit">Ajouter</button>
</form>
</Modal>
</div>
);
};
您收到的错误消息 SyntaxError: Unexpected token '<', "
要确认服务器是否确实返回了 HTML 响应,您可以尝试在控制台中打印响应文本:
const text = await response.text();
console.log(text);
这将使您能够看到服务器的完整响应,包括任何错误消息或 HTML 页面。
如果响应确实是 HTML,您将需要调查服务器端代码以查看导致错误的原因。您还可以尝试使用 Postman 等工具向同一端点发送 POST 请求,并查看是否收到预期的 JSON 响应。这可以帮助您确定问题是出在您的代码上还是服务器端代码上。