英文:
POSTing to a nodejs express backend with mongoose is failing
问题
我正在尝试使用此函数调用一个Node.js Express后端,并创建一个用户。我在前端使用的函数如下,后端是this。除了向mongoose模式添加一个字段之外,我没有对它进行任何更改。
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("http://localhost:3000/v1/auth/register", {
method: "POST",
body: JSON.stringify({
email: "test@aol.com",
password: "test1234",
name: "test",
//libraryCardId: "1234asdf",
// mobileNumber: mobileNumber,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setName("");
setEmail("");
setMessage("User created successfully");
} else {
setMessage("Some error occurred");
}
} catch (err) {
console.log(err);
}
};
我可以在Postman上使用以下JSON字符串来使其工作:
{
"name": "test",
"email": "test123@aol.com",
"password": "asdf1234"
}
但是,当我将它硬编码为上面所示的JSON字符串时,它会失败,mongoose验证器会说没有name、email或password。
英文:
I am trying to use this function to call a node.js express backend and create a user. The function I am using on the frontend is below and the back end is this. I have not made any changes to it other than to add a single field to the mongoose schema.
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("http://localhost:3000/v1/auth/register", {
method: "POST",
body: JSON.stringify({
email: "test@aol.com",
password: "test1234",
name: "test",
//libraryCardId: "1234asdf",
// mobileNumber: mobileNumber,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setName("");
setEmail("");
setMessage("User created successfully");
} else {
setMessage("Some error occured");
}
} catch (err) {
console.log(err);
}
};
I am able to get it working on Postman by using
{
"name": "test",
"email": "test123@aol.com",
"password": "asdf1234"
}
as a JSON string with the JSON setting, but when I insert that as the JSON string hardcoded (see above) it fails the mongoose validator saying that there is no name, email or password.
答案1
得分: 0
你需要在fetch中指定内容类型为application/json。
let res = await fetch('http://localhost:3000/v1/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'test@aol.com',
password: 'test1234',
name: 'test',
//libraryCardId: "1234asdf",
// mobileNumber: mobileNumber,
}),
});
英文:
You need to specify that the content type is application/json in the fetch.
let res = await fetch('http://localhost:3000/v1/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'test@aol.com',
password: 'test1234',
name: 'test',
//libraryCardId: "1234asdf",
// mobileNumber: mobileNumber,
}),
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论