我正在使用fetch()方法测试POST请求,并始终收到405(不允许使用方法)错误。 我正在使用Express 4.17.1和节点12.13.1 LTS
我已经在“真实机器”和虚拟机上对其进行了测试,结果相同。服务器和客户端都在同一台计算机上。
服务器(index.js)如下:
// import the express library
const express = require('express');
// create an app object that inherits the library
const app = express();
// get the app to listen
// the listen() function takes a port number and a callback function as arguments
app.listen(3000,() => console.log('listening on port 3000'));
// define the app root directory for static files
app.use(express.static('public'));
// set up a route to /api via the POST method
app.post('/api',(request,response)=>{
console.log(request);
});
客户端(index.html)如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
if ('geolocation' in navigator){
console.log('geolocation available');
navigator.geolocation.getcurrentPosition(position => {
const lat = position.coords.latitude;
const lon = position.coords.longitude;
document.getElementById('latitude').textContent = lat;
document.getElementById('longitude').textContent = lon;
const data = {lat,lon};
const options = {
method: 'POST',headers: {
'Content-Type': 'application/json'
},body: JSON.stringify(data)
};
fetch('/api',options);
});
} else {
console.log('geolocation unavailable')
}
</script>
<h1>The selfie app</h1>
<p>Latitude: <span id='latitude'></span>°<br>
longitude: <span id='longitude'></span>°</p>
</body>
</html>
Web应用程序的根目录是“ public”。 “ / api”是public的子目录(尽管我也尝试将“ / api”作为与“ public”相同级别的目录)。
我尝试了没有成功的body-parser和allow-methods库。
如果有人对发生的事情有任何解释,我将非常感激。