在node.js中发出POST请求并表达405(不允许方法)错误

我正在使用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库。

如果有人对发生的事情有任何解释,我将非常感激。

baizhongzheng 回答:在node.js中发出POST请求并表达405(不允许方法)错误

上面的

@Dijkstra确认我的代码有效。那使我着眼于我的工作流程。罪魁祸首是我正在使用的VSC扩展实时服务器。它将我的应用程序正在侦听的端口(3000)更改/转换为默认端口(5500)。可以在扩展的setting.json中进行调整。我更喜欢删除实时服务器。

,

我遇到了同样的问题,

对于app.post(),它总是响应该死的405,我必须暂时将.post更改为.get才能获得api的工作。

快递:4.17.1 Node.js:10.16.3

本文链接:https://www.f2er.com/3039333.html

大家都在问