error 400 bad request when sending a request using react(fetching data through react to django rest-framework)

jvlzgdj9  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(130)

我是新来的对这个职位的结构不熟悉请原谅。
所以我尝试使用以下链接将JSON数据发送到Django服务器

http://localhost:8000/profiles/

我一直在寻找几个小时,我做了一切可能解决的流行415错误,这是第一个错误.我尝试了所有可能的选项基于互联网,文章和答案在这里,最后的选项在create.jsx消除了第一个405错误相关的cors.现在我得到一个坏的请求,每当我试图发送数据.

这是我的React代码:

create.jsx

import { useState } from "react";

const Create = () => {
    const[name, setName] = useState("");
    const[email, setEmail] = useState("");
    const[mobile_number, setMobile] = useState("");
    const[national_id, setID] = useState("");
    const[password, setPassword] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    const blog = { name, email, mobile_number,national_id,password };

    const options={
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache',
      method: 'POST',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',
        'Access-Control-Allow-Methods': '*',
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
      body : JSON.stringify(blog)
    }

    fetch('http://localhost:8000/profiles/', options)
    .then(() => {
      console.log('new radiologist added');
    }).catch(error => {
        // handle the error here
        console.log(e);
    });
  }

  return (
    <div className="create">
      <h2>Add a New Blog</h2>
      <form onSubmit={handleSubmit}>
        <label>name:</label>
        <input 
          type="text" 
          required 
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
        <label>email:</label>
        <input 
          type="text" 
          required 
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <label>national id:</label>
        <input 
          type="text" 
          required 
          value={national_id}
          onChange={(e) => setID(e.target.value)}
        />
        <label> mobile phone </label>
        <input 
          type="text" 
          required 
          value={mobile_number}
          onChange={(e) => setMobile(e.target.value)}
        />
        <label> password </label>
        <input 
          type="text" 
          required 
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button>Sign up</button>
      </form>
    </div>
  );
}
 
export default Create;

Django模型:

class Radiologist(models.Model):
    name = models.CharField(max_length=100)
    id = models.AutoField(primary_key=True)
    email = models.EmailField(max_length=100, unique=True)
    mobile_number = models.CharField(max_length=10, unique=True)
    national_id = models.CharField(max_length=10, unique=True)
    password = models.CharField(max_length=100, default="123456")
    
    def __str__(self):
        return self.name

url模式

urlpatterns = [
    path("admin/", admin.site.urls),
    path("profiles/", ProfileList.as_view()),
    path("profile/<int:pk>", ProfileDetails.as_view()),
    path("profile/<int:pk>/patients", ProfilePatients.as_view()),

    
    path("patients/", PatientList.as_view()),
    path("patient/<int:pk>", PatientDetails.as_view()),
    path("patient/<int:pk>/scans", PatientScans.as_view()),

    path("scans/", ScanList.as_view()),
    path("scan/<int:pk>", ScanDetails.as_view()),
    
    path("scanNew/", ScanViewSet.as_view()),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我尝试了所有可能的选项(在名为options的常量中找到),我希望post请求能够毫无错误地发送到django服务器。

kcwpcxri

kcwpcxri1#

通常django会根据响应告诉你什么是错误,尝试使用任何rest API客户端(如postman)进行查询。或者检查开发人员工具。如果它在postman上工作,但在浏览器上不工作,那么你可能有cors error。安装cors header并确保它位于其他中间件之上。

相关问题