【问题标题】:405 (Method not allowed) error returned upon POST request in node.js and expressnode.js 和 express 中的 POST 请求返回 405(不允许的方法)错误
【发布时间】: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>&deg;<br>
    longitude: <span id='longitude'></span>&deg;</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


【解决方案1】:

双重检查端口

检查两端的日志以确认正在使用正确的端口。

上面的@Dijkstra 确认我的代码有效。这让我审视了我的工作流程。罪魁祸首是我使用的 VSC 扩展实时服务器。在我的情况下,它将我的应用程序正在侦听的端口(3000)更改/转换为默认端口(5500)。这可以在扩展的 setting.json 中进行调整。我更喜欢切断实时服务器。

【讨论】:

    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 2021-04-05
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多