【发布时间】:2020-08-05 20:00:21
【问题描述】:
我是 MEAN 堆栈的新手,正在尝试实现 express。出于某种原因,当导航到我已设置要处理的应用程序对象的路径时,我得到了 404。我知道应用程序必须正在运行,因为错误正在由我为处理 404 设置的自定义方法处理。
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongo = require('mongoose');
var db = mongo.connect("mongodb://localhost:27017/recipedb", function (err, response) {
if (err) { console.log(err); }
else { console.log('Connected to ' + db, ' + ', response) }
});
var app = express();
app.use(bodyParser());
app.use(bodyParser.json({ limit: 'Smb' }));
app.use(bodyParser.urlencoded({ extended: true }));
var Schema = mongo.Schema;
var categorySchema = new Schema({
id: { type: String },
name: { type: String }
}, {versionKey: false});
var cModel = mongo.model('category', categorySchema, 'category');
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
res.setHeader('Access-Control-Allow-Methods', 'GET','POST','OPTIONS','PUT','PATCH','DELETE',);
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.get("test", function (req, res) {
res.send('The GET Request was handled by express');
})
app.get("category", function (req, res) {
model.find({}, function (err, data) {
if (err) {
res.send(err);
}
else {
res.send(data);
}
});
}
)
app.use(function (req, res, next) {
res.status(404).send('Unable to find the requested resource!');
});
app.listen(3000, function () {
console.log('Rapid Recipes listening on port 3000...');
}
)
【问题讨论】:
-
如何在 app.get() 中加入“/test”而不是“test”?
-
你需要把
/放在前面!使用/test。 -
谢谢。这解决了这个问题。我以为我不需要 / 因为在我的 http 客户端中,我在发送请求时在主机名之后包含 /。尽管在 express 接收到该字符时会丢弃该字符,但这是有道理的。
-
@MarcusSantodonato 这正是我一个小时前写的第一个答案。看看答案! ????
标签: javascript node.js mongodb express