I am trying to send some data from my React frontend to my Django REST backend.
My Django application does NOT have models.
I have a react form. When the user submit the button, the form "submits" three params:
firmNAme
timeframes
numberOfResults
I want to send these three parameters to my Django backend. To do so, I m assuming React is sending a "POST" request to the Django endpoint. I need these params in Django so that I can use them to do some manipulations for a ML model.
My React function
handleSubmit(event){
event.preventDefault()
fetch("/myapi/getreactinfotwitter",{
method:"POST",
headers:{
'Accept':'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'data_options': {
'partnerName': this.state.firmName,
'timeframes': this.state.timeframes,
'numberOfResults': this.state.numberOfResults,
}
})
})
Now, I think the the Reast "POST" has to be matched with a Django "GET", so that Django gets the three params.
In DJANGO I have:
urls.py
path('getreactinfotwitter/', getreactinfotwitter, name="getreactinfotwitter")
myapi/views.py
@api_view(['GET', 'POST'])
def getreactinfotwitter(request):
print(request)
if request.method == 'GET':
return Response(request.data)
HOWEVER
My request in the views.py is not getting anything.
In the web console, when I click submit I get POST http://localhost:8080/myapi/getreactinfotwitter/ 500 (Internal Server Error)
Here are the steps to configure your React front-end with Django REST backend.
Django Settings:
django-cors-headers with the following command:pip install django-cors-headers
settings.py file:INSTALLED_APPS = (
##...
'corsheaders'
)
corsheaders.middleware.CorsMiddleware to the middleware classes in settings.pyMIDDLEWARE = [
# corsheaders middleware
'corsheaders.middleware.CorsMiddleware',
...
]
settings.py from where you want to get data. At the initial stage allow *ALLOWED_HOSTS = [*]
React Settings:
axios using the following command:npm i axios
React class.import React from "react";
...
import Axios from "axios";
...
yourFunctionName = () => {
Axios.post(`URL`, {
'partnerName': this.state.firmName,
'timeframes': this.state.timeframes,
'numberOfResults': this.state.numberOfResults,
},
{
headers: {
"Authorization": `AUTHORIZATION_KEY`,
"Content-Type": 'application/json'
}
}
)
.then(res => console.log(res))
.catch(error => console.err(error))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With