POST Requests from JS front to Django backend not working with Ngrok
I'm working on a web service with Python using Django. I used Ngrok to test it before deploying. My problem happens when the POST request I make in JavaScript in some endpoints just won't retreive any of the data required, instead they just return None. In the Django logs and the browser the response is 200 OK, but even in the logs the data isn't showing (I'm printing all the json data before return it).
This is the way I'm making the POST requests in JS
const url = 'http://localhost:8000/register_equipment/';
const data = {
"product": inputProduct.value,
"description": inputDescription.value,
"serial": inputSerial.value,
"warehouse_location": inputWarehouseLocation.value,
"shelf_location": inputShelfLocation.value,
"additional_location": inputAdditionalLocation.value,
"observations": inputObservations.value,
"quantity": inputQuantity.value,
"dedicated": dedicatedValues
};
// Request configuration
const options = {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken') // Add CSRF token header
},
body: JSON.stringify(data)
};
// Perform the request using fetch
fetch(url, options)
.then(response => {
if (response.ok) {
return response.json(); // Convert the response to JSON
}
throw new Error('Request failed');
})
.then(responseData => {
console.log(responseData.groups); // Handle response data
})
.catch(error => {
console.error('Error fetching group list:', error); // Handle errors
});
This is the function I'm using to retreive the CSRF Token
function 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();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
And this is the view of the request
@csrf_exempt
def register_equipment(request):
if not request.user.is_authenticated:
return redirect('login')
if request.method == 'POST':
# Get JSON data from the frontend
data = json.loads(request.body)
print(data)
print(data.get("dedicated"))
# Process location data
location = {
"warehouse": data.get("warehouse_location"),
"shelf": data.get("shelf_location"),
"additional": data.get("additional_location"),
}
# Process incoming data and save the equipment
try:
new_equipment = Equipment(
product=data.get("product"),
description=data.get("description"),
serial=data.get("serial"),
location=location,
observations=data.get("observations"),
dedicated=data.get("dedicated"),
quantity=data.get("quantity"),
available=True
)
new_equipment.save()
response_data = {'message': 'Equipment registered successfully'}
return JsonResponse(response_data)
except KeyError:
return JsonResponse({'error': 'Missing required data'}, status=400)
return JsonResponse({'error': 'Failed to register equipment'}, status=400)
Also, when trying to access from a different network, none of the requests work, they all send a CONNECTION_REFUSED error. I don't know if it's a problem in the way my back end is configured or if I made a mistake when setting up Ngrok.
I tried following the documentation and installed the CORS middleware but that didn't work either.
INSTALLED_APPS = [
...
"corsheaders",
...
]
MIDDLEWARE = [
...
"corsheaders.middleware.CorsMiddleware",
...
]
The thing that I don't understand is that the POST requests actually work (like in my login form) when the requests is made by the submit button and not in JavaScript.
<form method="post">
{% csrf_token %}
<div class="form-group">
<label for="username">Nombre de usuario:</label>
<input type="text" class="form-control" name="username" id="username" required>
</div>
<div class="form-group">
<label for="password">Contraseña:</label>
<input type="password" class="form-control" name="password" id="password" required>
</div>
<button type="submit" class="btn btn-primary btn-block">Iniciar sesión</button>
</form>
Any help I could get would be very appreciated.