【问题标题】:Node.JS Express - POST request not working (returning 404) - running in sub-directory on port 8080Node.JS Express - POST 请求不起作用(返回 404) - 在端口 8080 的子目录中运行
【发布时间】:2020-10-22 06:08:07
【问题描述】:

我有 2 个 node.js 服务器正在运行; 1 在端口 8000 另一个在 8080 端口

8080端口是API,所以需要向它发送POST请求。(端点:websocket/test)。 当我尝试这样做时,会返回 404。 它位于一个子目录(ROOT/webhook)中,所以不确定是不是这个原因,或者它是否在端口 8080 上?

Socket.io 工作正常,连接没有问题,我只是无法向该服务器发送 POST 请求。

这里是 server.js 文件:

//SOCKET.IO Server
const express = require('express');
const app = express();
const port = 8080;
const fs = require('fs');
const http = require('http');
const https = require('https');

const sslKey = 'HIDDEN';
const sslCert = 'HIDDEN';

const options = {
  key: fs.readFileSync(sslKey),
  cert: fs.readFileSync(sslCert)
};

const httpServer = http.createServer();
const httpsServer = https.createServer(options);

const io = require('socket.io')(httpsServer);

// FOR HTTP
// httpServer.listen(port, () => {
//     console.log("Socket.io http server is listening on port: " + port)
//     console.log(__dirname + '/key.pem');
// })
// FOR HTTPS
httpsServer.listen(port, () => {
    console.log("Socket.io https server is listening on port: " + port);
})

io.on('connection', function(socket){
  console.log('made socket connection', socket.id);
  socket.emit('welcome', 'Hiya! Welcome');
  app.post('/websocket/test', function() {
      console.log('webhook received');
      io.emit('webhook', 'You have received a webhook!');
  });
});

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    你几乎做对了。除非您没有告诉您的快速应用程序开始侦听请求。只需更改此代码:

    const httpsServer = https.createServer(options);
    

    到这里:

    const httpsServer = https.createServer(options, app);
    

    你的服务器应该可以工作了。

    【讨论】:

    • 添加了您的建议,但不幸的是,我仍然无法向服务器发送 POST 请求...我已经尝试了所有变体(使用:8080,没有完整的 URL,包括文件夹名称,等等)。从 PostMan 发帖时,它仍然会抛出 404 not found...
    • 如果我尝试通过浏览器 (DOMAIN:8080/webhook/test) 访问该页面,我得到:无法获取 /webhook/test。我添加了一个 app.get() ,它在加载页面时在浏览器中工作(然后无限加载)!但帖子仍然没有。而且 GET 也不在邮递员中......
    • 那么我认为你应该尝试在io.on("connection")处理程序之外注册路由。你的 socket.io 东西应该仍然有效。哦,不要尝试使用邮递员或任何东西访问您的发布路线......因为您没有告诉路线发送回复。
    猜你喜欢
    • 2022-01-19
    • 2021-01-05
    • 1970-01-01
    • 2018-06-20
    • 2020-12-18
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多