I am trying to send a PUT request through XMLHttpRequest but it return an empty using JS for the front end and nodejs for the backend. while in the network section in the dev tools, it shows that PUT is ok . I have been dealing with this for over 10 days, every iota of support will be highly appreciated. I really need this as I don't know what to do next. It's driving me nuts.
Below is my html
<body>
<form action="location.js" id="myLocation" method="PUT">
<br>
<div>
<label> location </label>
<input id="location" type="text" name="location" required>
</div>
<br>
<div>
<button type=submit>submit</button>
</div>
</form>
<div id="locate">
</div>
<a href="login.html"> GO TO LOGIN </a>
<script src="location.js"> </script>
<script src=""> </script>
</body>
Next is the JS for XMLHttpRequest
var form = document.getElementById('myLocation');
var display = document.getElementById('locate');
form.addEventListener('submit', sendData);
function sendData(e) {
e.preventDefault();
var location = document.getElementById('location').value;
var params = JSON.stringify({
"location": location
});
var val = params;
const XHR = new XMLHttpRequest();
XHR.onload = function () {
var out1 = this.responseText;
display.innerHTML = out1;
console.log(out1);
};
XHR.open('PUT', 'http://localhost:5000/parcel/:id/location', true);
XHR.setRequestHeader('Content-type', 'application/json; charset=utf-8');
XHR.setRequestHeader('Method', 'PUT');
XHR.send(val);
}
Below is the API router for the PUT request:
router.put('/:id/location', async (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, application/json;charset=utf-8");
res.setHeader("Access-Control-Allow-Method", "PUT");
let parcels
try {
const {_id} = req.params.id;
const {location} = req.body.location;
parcels = await parcel.findByIdAndUpdate(_id, location);
res.send(parcels);
} catch (err) {
console.log(err);
if (parcels == null) {
res.send('error nul')
} else{
res.send('unsuccesful')
}
}
});
XHR.open('PUT', 'http://localhost:5000/parcel/:id/location', true);
I think that :id is not right here.
Edit:
:id is a "route parameter". The listener can use it to cover a range of routes.
So if your API gets a GET request on /parcel/0001/location or /parcel/asd/location then the /parcel/:id/location handler can respond to all of them, and you can read the id from req.params.id.
You can only use this feature if you already know :id on the client side, and you can build it into the route e.g: "http://localhost:5000/parcel/"+id+"/location".