首页 > 解决方案 > 嵌套 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

标签: javascriptruby-on-railsjsonapi

解决方案


尝试JSON.stringify({ user })而不是JSON.stringify(user)为了创建嵌套字段。


推荐阅读