【发布时间】:2021-10-16 22:18:27
【问题描述】:
我有一个 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"
}
}
但不是通过获取
【问题讨论】:
-
关于您的编辑的一个问题:您是说您的 API 响应您的问题似乎与嵌套的 JSON 数据有关吗?这无关紧要;您应该提及您使用 Postman 发送的 请求。
标签: javascript ruby-on-rails json api