我对ExpressJS还是陌生的,只是与React结合设置了一个小的待办事项列表应用程序。我确实已经从mysql数据库中获得了待办事项列表,但正在为更新/插入数据库中的POST请求而苦苦挣扎。
当我打电话给http://localhost:9000/api/v1/todos/get时,路由器工作正常并返回了预期值。致电http://localhost:9000/api/v1/todos/add时,我总是收到404。
app.js
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let cors = require("cors");
let indexRouter = require('./routes/index');
let todosRouter = require('./routes/api/v1/todos');
let app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api/v1/todos', todosRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
todos.js
let express = require("express");
let router = express.Router();
let config = require("../../../config.json");
let mysql = require('mysql');
router.post("/add", function(req, res) {
// Do Something
res.send("added");
});
router.get("/get", function(req, res, next) {
let connection = mysql.createConnection({
host : config.dbHost,
user : config.dbUser,
password: config.dbPass
});
connection.connect();
connection.query('SELECT * FROM ' + config.dbName + '.`tablename`', function(err, rows, fields) {
if (err) throw err;
res.send(rows);
});
connection.end();
});
module.exports = router;
我在做什么错了?
答案 0 :(得分:0)
代码中没有错,问题可能出在客户端的HTTP请求方法上,请对/api/v1/todos/add
使用POST。我用您的代码创建了一个示例存储库,并添加了测试,请参阅github source repo和tests以获得更多的说明,尤其是this POST test.
答案 1 :(得分:0)