首页 > 解决方案 > Node.js - 带有 GET 处理程序的简单 Express 服务器不起作用

问题描述

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

// 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请求时,什么也没有发生。

这是怎么回事?

标签: javascriptnode.jsjsonhttpexpress

解决方案


First, you are not even requiring express, you are requiring a JSON file, so you should change that first line to:

const express = require('express');

Then, you need to call app.listen once you are done setting up your middleware, which you might be doing in a different file, but it's worth mentioning it.

So, all together with a few other small changes:

// 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 }!`));

If you run this with node <filename>.js after installing all the dependencies, you should see a message like App listening on port 3000! and then morgan will log a message for every incoming request automatically.

Note you can export your app instead of calling app.listen(...) at the end of the file with module.exports = app, but in that case you need to import that somewhere else (maybe you have a server.js file or something like that) and then call app.listen(...) there.


推荐阅读