请求快递路线时404

404 when making a request to express route

我正在尝试了解 express 及其处理路线的方式。

我设置了一个具有以下结构的域

/
  app.js
    /public_html
      index.html

在app.js中,我设置了我的快递服务器:

let app = express();

app.post('/list', (request, response) => {
  //get data then...
  response.send(data)
});

app.use(express.static('public_html'))

app.listen(3000, function(){
  console.log('listening');
});

我 运行 应用 node app.js

然后,在public_html目录中的index.html中,我正在尝试请求数据。我只是做了一个简单的:

fetch('/list').then(function(response) {
  console.log(response)
})

但我收到 404 作为响应。

我对一些事情有点困惑:

  1. 我的 Web 服务器 (Apache / Ubuntu) 默认设置为 public_html 目录外的 html 提供服务。这是否意味着我的整个节点应用程序结构需要移动到 public_html 文件夹中,而实际的 html 移动到 static 文件夹或其他文件夹中?

  2. 端口呢?节点应用程序在端口 3000 上侦听 - 但我不确定如何(或是否)专门向该端口发出请求。

  3. 路由路径 - 我发帖到 /list 但它应该是 ../list 吗?

我还没有找到适用于此应用的配置。任何帮助,将不胜感激。

使用以下代码。使用 ajax 而不是 fetch,方法必须是 POST。 Fetch 无法正常工作,因为默认情况下它是获取请求。

选项 1

    $.ajax({
       method: "POST",
       url: "/list"
      })
     .done(function( msg ) {
      alert( "Data " + msg );
  });

选项 2 仅将以下代码更改为 GET

=> POST
app.get('/list', (request, response) => {
  //get data then...
  response.send(data)
});

选项 3 在 fetch

中使用 POST
fetch("/list",
{
    method: "POST"
})
.then(function(data){  alert( "Data " + data ); })

感谢@vesse 建议选项 3

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

My web server (Apache / Ubuntu) is set up to serve html out of the public_html directory by default. Does that mean my whole node app structure needs to be moved into the public_html folder and the actual html moved into a static folder or something?

Node.js和Apache可以使用同一个静态文件夹而不冲突,但是它们不能监听同一个端口。您的 Apache 服务器很可能已经 运行 正在端口 80 上运行。如果您的 Node.js 服务器 运行 在端口 3000 上,对端口 80 的请求将与您在应用程序中编写的路由不匹配,并且因此 404 将 return(当然除非您在单独的 Apache 托管应用程序中有相同的路由)。

What about the port? The node app listens on port 3000 - but I'm not sure how (or if) to make a request to that port specifically.

因为 Apache 可能已经在侦听端口 80,所以您发送到 http://localhost will hit your Apache server. Instead, you must make requests that include a port number, http://localhost:3000 的任何请求都会到达您的 Node.js 服务器。

Route path - I am posting to /list but should it be ../list?

不,您应该 post 到 /list 并考虑 Rakesh 在他的回答中提出的所有要点,以便您正确地将 POST 匹配到 POST 从客户端到服务器或交换机如果那更合适的话,可以得到。与第二点一样,请确保您正在 posting 到 http://localhost:3000 and not just http://localhost。正如您所指出的,一个是 Apache,另一个是 Node.js

最后,这是我从与我的应用程序脚本相邻的文件夹提供服务时使用的静态服务器代码行:

app.use('/', express.static(__dirname + '/public_html'));

有了这个,您放在 public_html 文件夹中的所有文件都可以在您的应用程序中导航,其中还包括与 Apache 相关的所有内容。注意 __dirname 始终是当前执行脚本所在的目录 运行。要访问此站点,只需在浏览器中转到 http://localhost:3000,您应该会看到索引文件。