javascript - 嵌套 JSON 数据以发送到 API
问题描述
我有一个 Rails API,我试图以这种格式从反应前端发送 JSON 数据:
{
"user" : {
"email": "daves@email.com"
"password": "dave123"
"password_confirmation": "dave123"
"subject": "david"
"teacher": "student"
"username": "mikey"
}
}
它显然嵌套在“用户”中,但我的代码目前只是在没有用户包裹的情况下发送它,并且 API 不喜欢 JSON 格式
Signup.js:18 POST http://localhost:3001/api/users net::ERR_ABORTED 422 (Unprocessable Entity)
}
email: "daves@email.com"
password: "dave123"
password_confirmation: "dave123"
subject: "david"
teacher: "student"
username: "mikey"
}
如何以正确的格式将 JSON 发送到 API?,这是登录提交页面的javascript
import React from 'react'
import { useState } from 'react'
// import axios from 'axios'
export default function Signup() {
const [teacher, setUserType] = useState("student");
const [subject, setSubject] = useState(" ");
const [email, setEmail] = useState("email");
const [password, setPassword] = useState("password");
const [password_confirmation, setConfirmedPassword] = useState("confirm password");
const username = "mikey"
const handleSubmit = (e) => {
e.preventDefault();
const user = {teacher, subject, email, password, password_confirmation, username}
console.log(user)
fetch('http://localhost:3001/api/users', {
mode: 'no-cors',
method: 'POST',
headers: { "Content-Type": "application/json"},
body: JSON.stringify(user)
}).then(() => {
console.log(user)
})
}
return (
<div className="signup-form">
<form onSubmit={handleSubmit}>
<label>
<input
type="radio"
value={teacher}
onChange={(e) => setUserType(e.target.value)}
/>
Student
</label>
<label>
<input
type="radio"
value={teacher}
onChange={(e) => setUserType(e.target.value)}
/>
Tutor
</label>
<label>Subject</label>
<input
type="text"
required
placeholder=" "
onChange={(e) => setSubject(e.target.value)}
/><br/>
<label>Email address</label>
<input
type="text"
required
placeholder="email"
onChange={(e) => setEmail(e.target.value)}
/><br/>
<label>New password</label>
<input
type="text"
required
placeholder="choose password"
onChange={(e) => setPassword(e.target.value)}
/><br/>
<label>Confirm password</label>
<input
type="text"
required
placeholder="confirm password"
onChange={(e) => setConfirmedPassword(e.target.value)}
/>
<button>Submit</button>
</form>
</div>
);
}
谢谢
补充一下,我已经能够在邮递员中提交一个帖子请求,它返回:
{
"user": {
"id": 4,
"email": "testesr@testing.com",
"username": "fffmike",
"subject": null,
"teacher": null,
"token": "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6NCwiZXhwIjoxNjM0MDYxOTkwfQ.8qLlB5wwPGSCsxtkzjuEIxw8PFbLKoM_fo9UllNsonQ"
}
}
但不是通过 fetch
解决方案
尝试JSON.stringify({ user })
而不是JSON.stringify(user)
为了创建嵌套字段。
推荐阅读
- unit-testing - 如何通过 io.mockk 测试使用不同参数多次调用的方法?
- angular - Angular 7 风格不同层次的垫子树
- javascript - 在 Extjs 3.4 中渲染之前格式化加载数据
- .net-core - 如何首先从表数据库更新模型
- c# - 我想获取两个日期之间的记录,但日期列在数据库中是字符串格式。使用 linq 查询
- javascript - How to create an array from object which has specific properties in child objects
- python - 如何从python中找到dll函数?
- javascript - 如何同时处理保存多对多关系?
- amazon-web-services - 在分区中插入带有特殊字符的 Hive 表
- excel - 宏不起作用:“编译错误:不支持对象库功能”