我正在使用Django Rest Framework和Bootstrap-React开发电子处方Web应用程序。 但是我遇到一个错误,说 POST http://127.0.0.1:8000/api/prescription-view/ 400(错误请求)
如何解决此问题?顺便说一下,这是我的代码:
settings.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',
]
views.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)
serializers.py
class PrescriptionSerializerView(serializers.ModelSerializer):
class Meta:
model = Prescription
fields = ['drug_name' , 'dosage' , 'route', 'frequency', 'amount_dispensed', 'no_of_refills']
Form.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。如何解决此问题?
答案 0 :(得分:0)
当您遇到此类错误时:
Content-type
应该是Content-Type
?也许您也想念Accept
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
@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响应的更多详细信息。