【发布时间】:2020-03-20 07:22:04
【问题描述】:
我正在使用 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 库,但没有成功。
如果有人能解释发生了什么,我将不胜感激。
【问题讨论】:
-
只是为了让您知道,我复制了一个粘贴的服务器代码,并使用 http 客户端向
localhost:3000/api发送了一个发布请求。成功执行console.log(request);。 -
@Dijkstra 感谢您抽出宝贵时间。这让我走上了正轨。
标签: node.js express post fetch-api http-status-code-405