【问题标题】:Node.js - Simple Express server with GET handler not workingNode.js - 带有 GET 处理程序的简单 Express 服务器不起作用
【发布时间】:2019-05-03 13:12:31
【问题描述】:

我正在尝试在 Express.js 中创建一个 GET 请求处理程序,如下所示:

// import files and packages up here

const express = require('./data.json');
var app = express();
var morgan = require ('morgan')
const port = 3000;
console.log(express)

// create your express server below

// add your routes and middleware below

app.get('/', function (req, res, next) {
    res.writeHead(200)
    res.send('USER')
    console.log(express)
})

// export the express application
module.exports = app;

但它不起作用,所以当我发送 GET 请求时,什么也没有发生。

发生了什么事?

【问题讨论】:

  • 这应该会在您运行程序时引发错误。你是如何尝试运行Express.js的?

标签: javascript node.js json http express


【解决方案1】:

首先,您甚至不需要express,您需要一个 JSON 文件,因此您应该将第一行更改为:

const express = require('express');

然后,您需要在完成设置中间件后调用app.listen,这可能是在不同的文件中进行的,但值得一提。

所以,再加上一些其他的小改动:

// Why?
// const express = require('./data.json');

// It should be like this instead:
const express = require('express');

// And if you want to require a JSON file anyway to send it back:
const data = require('./data.json');

// Require morgan:
const morgan = require('morgan')

// Create the express app:
const app = express();

// Use morgan's middleware in your express app:
app.use(morgan('combined'));

// Define the port to run the server at:
const port = 3000;

// Define your GET / route:
app.get('/', (req, res, next) => {
    // Send status code + text message:
    res.status(200).send('USER');

    // Or if you prefer to send JSON data:
    // res.status(200).json(data);
});

// Start listening on that port:
app.listen(port, () => console.log(`App listening on port ${ port }!`));

如果您在安装所有依赖项后使用node <filename>.js 运行此程序,您应该会看到类似App listening on port 3000! 的消息,然后morgan 将自动记录每个传入请求的消息。

请注意,您可以导出您的应用程序,而不是在文件末尾使用module.exports = app 调用app.listen(...),但在这种情况下,您需要将其导入其他地方(也许您有一个server.js 文件或类似的东西) 然后在那里打电话给app.listen(...)

【讨论】:

  • 我之所以有 ( const express = require('./data.json') 是因为我需要抓取该文件中的数据并将其显示在网页上。我想使用 require(data .json) 会工作
  • 是的,你是对的,但那是另一回事。然后你应该做类似const data = require('./data.json')的事情,但仍然需要express。看看这个:stackoverflow.com/questions/44849082/…
  • 您的建议很有帮助!我是编程新手,这是我在 node 上工作的第一周
猜你喜欢
  • 2015-03-11
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 2012-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
相关资源
最近更新 更多