当我向https://localhost:3443/images/
端点发送GET请求时,得到以下结果:
[
{
"_id": "5e8ef5fa98c70f30a8986070",
"createdAt": "2020-04-09T10:16:26.796Z",
"updatedAt": "2020-04-09T10:16:26.796Z",
"__v": 0
},
{
"_id": "5e8efb70070f0b39103cba71",
"createdAt": "2020-04-09T10:39:44.196Z",
"updatedAt": "2020-04-09T10:39:44.196Z",
"__v": 0
},
{
"_id": "5e90150dd9812057f81784f3",
"createdAt": "2020-04-10T06:41:17.633Z",
"updatedAt": "2020-04-10T06:41:17.633Z",
"__v": 0
}
]
但是,当我尝试将每个id添加到我的URL末尾(如https://localhost:3443/images/5e90150dd9812057f81784f3
时,它会给我Not Found 404
错误消息。
我的app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var usersRouter = require('./routes/usersRouter');
var imagesRouter = require('./routes/imagesRouter');
const uploadRouter = require('./routes/uploadRouter');
const Images = require('./models/images');
//const uploadRouter = require('./routes/uploadRouter');
//const favoriteRouter = require('./routes/favoriteRouter')
var config = require('./config');
const mongoose = require('mongoose');
//mongoose.set('useCreateIndex', true);
mongoose.Promise = require('bluebird');
var passport = require('passport');
var authenticate = require('./authenticate');
// Connection URL
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
//useMongoClient: true,
/* other options */
useNewUrlParser: true ,
useUnifiedTopology: true
});
connect.then((db) => {
console.log("Connected correctly to server");
}, (err) => { console.log(err); });
var app = express();
// Secure traffic only
app.all('*', (req, res, next) => {
if (req.secure) {
return next();
}
else {
res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use('/', index);
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/images',imagesRouter);
app.use('/imageUpload',uploadRouter);
//app.use('/imageUpload',uploadRouter);
//app.use('/favorites',favoriteRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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;
我的imageRouter.js:
const express = require('express');
const bodyParser = require('body-parser');
const Images = require('../models/images');
var authenticate = require('../authenticate');
const imagesRouter = express.Router();
const cors = require('./cors');
imagesRouter.use(bodyParser.json());
imagesRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } );
imagesRouter.route('/')
//.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Images.find({})
.then((images) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(images);
}, (err) => next(err))
.catch((err) => next(err));
})
module.exports = imagesRouter;
答案 0 :(得分:3)
您必须为查询参数定义一个端点。
app.get("/images/:id",async (req,res)=>{
const id=req.params.id
const image=await Images.findById(id)
if(!image) res.send(`no image exists with given ${id}`)
res.send(image))
})
因为您使用的是猫鼬,所以您必须有一个模型。我只是命名为Images,并且应该将其导入您要查询的同一页面上。
在猫鼬中,所有查询操作都是异步操作。