首页 > 解决方案 > 提交时Django和React总是错误请求

问题描述

我正在使用 Django Rest Framework 和 Bootstrap-React 开发电子处方 Web 应用程序。但我面临一个错误,说POST http://127.0.0.1:8000/api/prescription-view/ 400 (Bad Request)

如何解决这个问题?顺便说一句,这是我的代码:

设置.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'corsheaders',
    
    'prescribe_app',
]

CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

视图.py

@api_view(['GET', 'POST'])
def prescription_view(request):

    if request.method == 'GET':
        prescription = Prescription.objects.all()
        serializer = PrescriptionSerializerView(prescription, many=True)
        return Response(serializer.data)
    
    elif request.method == 'POST' :
        
        serializer = PrescriptionSerializerView(data=request.data)
        if serializer.is_valid():
            serializer.save()
        else:
            content = {'Error': 'Invalid data'}
            return Response(content,status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.data)

序列化程序.py

class PrescriptionSerializerView(serializers.ModelSerializer):
    class Meta:
        model = Prescription
        fields = ['drug_name' , 'dosage' , 'route', 'frequency', 'amount_dispensed', 'no_of_refills']

表单.js

import React from  'react';
import { Row, Card, Col, Table, Form, Button} from 'react-bootstrap';


class FormPage extends React.Component{


    constructor(props){
        super(props);
        this.state = {
            prescriptionList: [],
            activeItem: {
                id:null,
                drug_name:'',
                dosage:'',
                route:'',
                frequency:'',
                amount_dispensed:'',
                no_of_refills:''

            },
            editing:false,
        }
            this.viewPrescription = this.viewPrescription.bind(this)
            this.handleChange = this.handleChange.bind(this)
            this.handleSubmit = this.handleSubmit.bind(this)
            this.getCookie = this.getCookie.bind(this)
            // this.deleteItem = this.deleteItem.bind(this)
            // this.startEdit = this.startEdit.bind(this)
            // this.strikeUnstrike = this.strikeUnstrike.bind(this)
    };

    getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    // R E T R I E V I N G   D A T A  F R O M   A P I
    componentDidMount(){
        this.viewPrescription()
    }

    viewPrescription(){
    console.log('Fetching ...' )

        fetch('http://127.0.0.1:8000/api/prescription-view/')
            .then(response => response.json())
            .then(data =>
                // console.log("Prescription" , data)
            this.setState({
                prescriptionList:data
            })
        )
        
    }
    
    handleChange(e){
        var name = e.target.name
        var value = e.target.value
        console.log('Name:', name)
        console.log('Value:', value)

        this.setState({
            activeItem:{
                ...this.state.activeItem,
                title:value
            }
        })
    }

    // S U B M I T T I N G   D A T A  T O   A P I

    handleSubmit(e){
        e.preventDefault()
        // console.log('Prescription : ', this.state.achieveItem)

        var csrftoken = this.getCookie('csrftoken')

        // var url = 'http://127.0.0.1:8000/api/prescription-view/'

        fetch('http://127.0.0.1:8000/api/prescription-view/', {
            method: 'POST' ,
            headers: {
                'Content-type' : 'application/json',
                'X-CSRFToken' : csrftoken,
                
                },
                body: JSON.stringify(this.state.activeItem)
            }).then((response) =>  {
                    this.viewPrescription()
                    this.setState({
                    activeItem: {
                        id:null,
                        drug_name:'',
                        dosage:'',
                        route:'',
                        frequency:'',
                        amount_dispensed:'',
                        no_of_refills:'',
                    }
                    })
            }).catch(function(error){
                console.log('ERROR', error)
            })
        }
        
    

    render(){
        var prescriptionView = this.state.prescriptionList
        // var self = this
        return(
            <div style={{padding: '1rem'}}>
                <Card style={{ marginTop: '5px' }}>
                <Card.Header style={{backgroundColor: '#00A0DC', color: 'white'}}>Patient Information</Card.Header>
                    <Card.Body>
                        <Row>

                            <Col>
                                <h4>Donald Biden</h4>
                                <Card style={{padding: '10px', fontSize: '12px'}}>
                                <Table borderless size="sm">
                                
                                    <tbody>
                                        <tr>
                                        <td>Age</td>
                                        <td>:</td>
                                        <td>55 yrs old</td>
                                        </tr>
                                        <tr>
                                        <td>Address</td>
                                        <td>:</td>
                                        <td>San Pablo, Laguna</td>
                                        </tr>
                                        <tr>
                                        <td>Birthday</td>
                                        <td>:</td>
                                        <td>September 09, 1965</td>
                                        </tr>
                                    </tbody>
                                </Table>
                                </Card>
                                
                            </Col>

                            <Col>  
                            {prescriptionView.map(function(prescriptionView, index){
                                return(
                                    <div key={index}>
    
                                        <Card style={{ marginTop: '5px' , fontSize: '12px'}}>
                                            <Card.Header>Medication Information</Card.Header>
                                            <Card.Body>
                                            <Table borderless size="sm">
                                                <tbody>
                                                    <tr>
                                                    <td>Drug Name</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.drug_name}</td>
                                                    </tr>
                                                    <tr>
                                                    <td>Dosage</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.dosage} mgs</td>
                                                    </tr>
                                                    <tr>
                                                    <td>Route Taken</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.route}</td>
                                                    </tr>
                                                    <tr>
                                                    <td>Frequency</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.frequency}</td>
                                                    </tr>
                                                    <tr>
                                                    <td>Amount Dispensed</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.amount_dispensed}</td>
                                                    </tr>
                                                    <tr>
                                                    <td>No of Refills</td>
                                                    <td>:</td>
                                                    <td>{prescriptionView.amount_dispensed}</td>
                                                    </tr>
                                                </tbody>
                                            </Table>
                                            </Card.Body>
                                        </Card>
                                    </div>
                                    )
                            })}
                                
                            </Col>

                        </Row>
                    </Card.Body>
                </Card>

                <Card style={{ marginTop: '1rem', marginBottom: '5rem' }}>
                <Card.Header style={{backgroundColor: '#00A0DC', color: 'white'}}>Prescription Information</Card.Header>
                    <Card.Body style={{fontSize: '11px'}}>
                        <Form onSubmit={this.handleSubmit} id="form">
                            <Row>
                                <Col>
                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Medicine Name
                                        </Form.Label>
                                        <Col sm="10">
                                        
                                        <Form.Control size="sm" placeholder="Medicine Name" id="drug_name" type="text" onCha />
                                        </Col>
                                    </Form.Group>

                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Dosage
                                        </Form.Label>
                                        <Col sm="10">
                                        <Form.Control size="sm" type="number" placeholder="Dosage" id="dosage"  />
                                        </Col>
                                    </Form.Group>

                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Route Taken
                                        </Form.Label>
                                        <Col sm="10">
                                        <Form.Control size="sm" placeholder="" id="route" type="text"  />
                                        </Col>
                                    </Form.Group>

                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Frequency
                                        </Form.Label>
                                        <Col sm="10">
                                        <Form.Control size="sm" placeholder="" id="frequency" type="text"  />
                                        </Col>
                                    </Form.Group>
                                </Col>

                                <Col>
                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Amount Dispensed
                                        </Form.Label>
                                        <Col sm="10">
                                        <Form.Control size="sm" type="number" id="amount_dispensed" placeholder="Medicine Name"  />
                                        </Col>
                                    </Form.Group>

                                    <Form.Group as={Row}>
                                        <Form.Label column sm="2">
                                        Number of Refills
                                        </Form.Label>
                                        <Col sm="10">
                                        <Form.Control size="sm" type="number" id="no_of_refills" placeholder="Dosage"  />
                                        </Col>
                                    </Form.Group>

                                    

                                    <Button variant="primary" size="sm" md={{ span: 4, offset: 4 }} id="submit" type="submit" >
                                        Submit
                                    </Button>

                                </Col>
                            </Row>
                        </Form>
                    </Card.Body>
                </Card>
            </div>
        )
    }
};

export default FormPage;

当我点击提交按钮时,什么都没有提交。然后当我查看我的控制台时,它显示错误和错误请求 400。如何解决这个问题?

标签: pythonreactjsdjangodjango-rest-frameworkdjango-react

解决方案


当您遇到此类错误时:

  • 如果请求看起来像您想要的,请检查浏览器开发人员工具。例如,您发送的数据是否正确?请仔细检查标题。也许Content-type应该是Content-Type?也许你也想念Accept
headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
},
  • 如果请求看起来不错。然后尝试检查您在 django 开发服务器中的错误详细信息。有时我添加有助于调试问题所在的打印:
@api_view(['GET', 'POST'])
def prescription_view(request):
    print("URL enpoint works!")
    if request.method == 'GET':
        prescription = Prescription.objects.all()
        serializer = PrescriptionSerializerView(prescription, many=True)
        return Response(serializer.data)
    
    elif request.method == 'POST' :
        print("This is POST with data", request.data)
        serializer = PrescriptionSerializerView(data=request.data)
        print("serializer works")
        if serializer.is_valid():
            print("try to save ...")
            serializer.save()
        else:
            print("serializer not valid")
            content = {'Error': 'Invalid data'}
            return Response(content,status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.data)

尝试使用其他打印运行 django。如果您仍然有问题,请使用有关请求和 django 响应的更多详细信息更新评论。


推荐阅读