简体   繁体   English

为什么node.js找不到我的HTML页面

[英]Why is node.js not finding my HTML pages

I have a test directory C:\\node_samples\\hello_express set up: 我设置了一个测试目录C:\\ node_samples \\ hello_express

在此处输入图片说明

I have a package.json file in the test directory: 我在测试目录中有一个package.json文件:

{
  "name": "hello_express",
  "version": "0.0.0",
  "description": "A simple web site",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Pieter Geerkens",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "express": "4.13.4",
    "formidable":  "1.x"
  }
}

I have node.js , express and formidable properly installed in a ../node_modules subdirectory (at least, success reported from the install.) by running this command from the test directory: 通过在测试目录中运行以下命令,我可以在../node_modules子目录(至少,从安装中报告成功)中正确安装了node.jsexpress强大代码:

npm install 

I have an app.js file located in the test directory: 我在测试目录中有一个app.js文件:

var express = require('express');
var app = express();
var formidable = require('formidable');

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

app.post('/SubmitHelloPost', function (request, response) {
   if (request.method.toLowerCase() == 'post') {
      // parse form data
      var form = new formidable.IncomingForm();
      form.parse(request, function (err, fields) {
         response.writeHead(200, { 'Content-Type': 'text/html' });
         response.write('Hello ' + fields.userName + '!<br />');
         response.end('Have a POST great day!');
         console.log('Handled POST request from ' + fields.userName);
      });
   }
});

app.get('/SubmitHello', function (request, response) {
   response.writeHead(200, { 'Content-Type': 'text/html' });
   response.write('Hello ' + request.query.userName + '!<br />');
   response.end('Have a great day!');
   console.log('Handled GET request from ' + request.query.userName);
});

var port = 8081;
app.listen(port);
console.log('Listening on port: ' + port);

I open a command prompt and run node app as follows: 我打开命令提示符并运行节点应用程序 ,如下所示:

在此处输入图片说明

However when I attempt to run the test by navigating to either of: 但是,当我尝试通过导航至以下任意一个来运行测试时:

http://localhost:8081/HelloForm.html
http://localhost:8081/HelloPost.html

I get an Error 404. 我收到错误404。

The html files are ( HelloForm.html ): html文件为( HelloForm.html ):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title></title>
   <meta charset="utf-8" />
</head>
<body>
   <form method="get" action="/SubmitHello">
      Enter Name: <input type="text" name="userName" autofocus />
      <input type="submit" value="Submit" />
   </form>
</body>
</html>

and (HelloPost.html*): 和(HelloPost.html *):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title></title>
   <meta charset="utf-8" />
</head>
<body>
   <form method="post" action="/SubmitHelloPost">
      Enter Name: <input type="text" name="userName" autofocus />
      <input type="submit" value="Submit" />
   </form>
</body>
</html>

I have no idea what is wrong. 我不知道怎么了。 everything worked briefly after I first set it up, then stopped working. 在我首先进行设置之后,一切都短暂运行,然后停止工作。

I think your problem is caused by the following line: 我认为您的问题是由以下几行引起的:

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

This tells Express that when it receives requests starting with /forms , it should map those to static files in the /public folder. 这告诉Express,当它接收到以/forms开头的请求时,应将其映射到/public文件夹中的静态文件。 From your directory structure, I think this is what you're trying to do: 从您的目录结构来看,我认为这是您想要做的:

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

(It's still a good idea to move your static files to a separate directory though. Right now, navigating to http://localhost:8081/app.js would return the raw server-side code, which you probably don't want to be readable from your client-side code.) (尽管将静态文件移动到一个单独的目录仍然是一个好主意。现在,导航到http://localhost:8081/app.js将返回原始的服务器端代码,您可能不想这样做可以从您的客户端代码中读取)。

You should make a directory for those files (I'll use 'public' for this example). 您应该为这些文件创建一个目录(在本示例中,我将使用“ public”)。 Then move the files you want to serve to it, and then change 然后将您要提供的文件移至该文件,然后进行更改

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

to

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

The first argument is the server directory where clients access the files, which you want to be the root directory (ie '/'), and the second argument is where the files are stored. 第一个参数是客户端访问文件的服务器目录,您要将其作为根目录(即“ /”),第二个参数是文件的存储位置。 Usually you don't want to mix your public content (like html), with private content, like server logic, so you put it in a separate folder and only serve that content. 通常,您不想将公共内容(例如html)与私有内容(例如服务器逻辑)混合在一起,因此您将其放在单独的文件夹中,仅提供该内容。

It looks like there are at least 2 problems. 看来至少有2个问题。

Problem #1 问题1

You've mounted your static asset directory at the /forms path, meaning any static assets you want to retrieve will be found at http://localhost:8081/forms/SomeFileName . 您已经将静态资产目录安装在/forms路径中,这意味着要检索的任何静态资产都可以在http://localhost:8081/forms/SomeFileName You are trying to locate them directly at http://localhost:8081/HelloForm.html , which won't work. 您正在尝试直接在http://localhost:8081/HelloForm.html上找到它们,该方法将不起作用。 If you want to get rid of the /forms part of the path entirely, then you can remove the path argument entirely from your static asset declaration: 如果您想完全摆脱路径的/forms部分,则可以从静态资产声明中完全删除path参数:

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

Problem #2 问题二

You don't have these files inside the public directory anyway. 无论如何,您在公共目录中都没有这些文件。 They're just sitting out in your root directory. 他们只是坐在您的根目录中。 Instead you want them to be inside a folder called public , so that your static asset declaration can find them. 相反,您希望它们位于名为public的文件夹中,以便您的静态资产声明可以找到它们。 That's why it has the word public in it, like so: 这就是为什么它包含public一词的原因,如下所示:

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

So instead, create a folder in the root directory called public and move both those files (HelloForm.html and HelloPost.html) into there. 因此,请在根目录中创建一个名为public的文件夹,并将这两个文件(HelloForm.html和HelloPost.html)都移动到该目录中。

Here are the Express docs on static file serving , which show you how it works in more detail. 这是有关静态文件服务Express文档 ,向您详细介绍了它的工作方式。

However, I'm guessing that even though this will work to display those 2 files, this is probably not what you ultimately want to do. 但是,我猜测即使这可以显示这两个文件,但这也可能不是您最终想要的。 My guess is that you want to use the 2 routes you've defined to show these 2 pages. 我的猜测是您想使用定义的2条路线显示这2页。 My recommendation would be to read up on using a View Engine like EJS to render dynamic views, and also read up on RESTful routing to determine how to name your routes. 我的建议是继续阅读使用诸如EJS之类的View Engine呈现动态视图的知识,并继续阅读RESTful路由以确定如何命名您的路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM