I'm working through a Coding Train tutorial on data and APIs, but I got to a point where I keep getting a 405 error when trying to make a POST request.
if ('geolocation' in navigator) { console.log('geolocation available'); navigator.geolocation.getCurrentPosition(position => { console.log(position.coords.latitude, position.coords.longitude); const lat = position.coords.latitude.toFixed(2); const lng = position.coords.longitude.toFixed(2); const latDisp = document.getElementById("lat"); const lngDisp = document.getElementById("lng"); latDisp.innerText = lat; lngDisp.innerText = lng; const data = { lat, lng }; const options = { method: 'POST', headers: { "Content-Type": "application/json", }, body: JSON.stringify(data) }; fetch('/api', options); });} else { console.error('geolocation IS NOT avaiable');}
if ('geolocation' in navigator) { console.log('geolocation available'); navigator.geolocation.getCurrentPosition(position => { console.log(position.coords.latitude, position.coords.longitude); const lat = position.coords.latitude.toFixed(2); const lng = position.coords.longitude.toFixed(2); const latDisp = document.getElementById("lat"); const lngDisp = document.getElementById("lng"); latDisp.innerText = lat; lngDisp.innerText = lng; const data = { lat, lng }; const options = { method: 'POST', headers: { "Content-Type": "application/json", }, body: JSON.stringify(data) }; fetch('/api', options); });} else { console.error('geolocation IS NOT avaiable');}
In the console I get:
geolocation available
geolocation available
[my lat] [my lng]
[my lat] [my lng]
POST http... net::ERR_ABORTED 405 (Method Not Allowed)
POST http... net::ERR_ABORTED 405 (Method Not Allowed)
If I go to Network in the dev tools in Chrome and open the item with the error I can see that the Response Headers > Allow: GET, HEAD, OPTIONS. I'm not sure why POST is not allowed.