第一次在此处使用express。
我的app.js
文件中有以下内容:
const express = require("express");
const mysql = require("mysql");
const app = express();
const PORT = process.env.PORT || 8000;
const connection = mysql.createConnection({
host: "localhost",
user: "admin",
password: "password",
database: "mydb",
});
app.use(express.static(__dirname + "/express"));
app.use(express.urlencoded()); // have also tried with "extended: true" and "extended: false"
app.use(express.json());
// GET
app.get("/getAllUserActivity", (req, res) => {
const order = req.query.order || "id";
const page = req.query.page || 0;
const limit = req.query.limit || 100;
connection.connect((err) => {
if (err) throw err;
connection.query(
"SELECT id, username, counter FROM users ORDER BY ? LIMIT ?,?",
[order, page, limit],
(err, results, fields) => {
if (err) throw err;
res.send(results);
}
);
});
});
// POST
app.post("/updateUserActivity", (req, res) => {
const userId = req.body.userId;
const username = req.body.username;
const counter = req.body.counter;
connection.connect((err) => {
if (err) throw err;
connection.query(
"INSERT INTO users (id, username, counter) VALUES (?, ?) ON DUPLICATE KEY UPDATE counter = counter + ?",
[userId, username, counter],
(err, results, fields) => {
if (err) throw err;
res.send(results);
}
);
});
});
我的POST请求具有标题"Content-Type": "application/x-www-form-urlencoded"
。
我面临的问题有两个:
- GET请求每隔一次失败。第一次它返回期望的数据,但第二次我得到
Incomplete response received from application
-repeat - 我只能让POST或get请求工作,这取决于我如何设置中间件。如何在此处同时拥有GET和POST
这里的老php用户,试图弄清楚Express。谢谢
将所有if (err) throw err;
替换为向客户端发送实际错误响应。您必须始终对每个传入的请求发送某种形式的响应。遗憾的是,许多演示代码都显示了if (err) throw err;
,因为在异步回调中,这几乎从来都不是正确的代码。
然后(尽管我不知道你的数据库的具体细节(,你需要在使用后释放/关闭你的数据库连接,这样它们就不会泄漏。或者,您可以使用一组连接池,在执行查询后,这些连接会自动返回到池中。