javascript - 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
请求时,什么也没有发生。
这是怎么回事?
解决方案
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.
推荐阅读
- python - 从跨度中提取文本
- php - 更新到 PHP 7.4 后的错误:未捕获的错误:调用数组上的成员函数 find()
- kubectl - k8s 集群上的“kubectl get”cli 响应时间太长
- javascript - HTTP 响应中缺少 react-admin
- c# - 在 Visual Studio 2019 社区中将 Azure API 链接到 C# ASP.Net 项目的问题
- java - 使用 Jolt 对键进行 JSON 到 JSON 转换
- angular - 为 Angular 项目混合引导程序和谷歌材料
- mysql - 选择非英文文本的行
- swiftui - 如何在 SwiftUI 中从登录屏幕转到主屏幕
- functional-programming - 为什么使用 goto 被认为是不好的做法,但 call/cc 不是?