我正在努力在express js中制作REST API,但出现错误“无法获取/ api / bears”。 这是我的代码
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Bear = require('./app/models/bear');
mongoose.connect('mongodb://localhost/api', { useNewUrlParser: true }); // connect to our database
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 3000;
//routes for api
var router = express.Router();
router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});
router.get('/',function(req,res){
res.json({message: "Welcome to my Api"});
});
router.route('/bears')
.post(function(req,res){
var bear = new Bear();
bear.name = req.body.name;
bear.save(function(err){
if(err)
{
res.send(err);
}
res.json({message: 'bear created!'});
});
});
app.use('/api', router);
app.listen(port);
console.log("Magic happens on port" + port);
app / models / bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
在localhost:3000 / api上,一切正常,但是在localhost:3000 / api / bears上,我得到无法获取/ api / bears
有人可以帮助我我想念的地方吗?
答案 0 :(得分:1)
您肯定会收到此错误
无法获取/ api / bears
第二个单词在这里很重要:GET
您使用:
定义了路线router.route('/bears').post(function(req,res){ [...] })
如果您发送GET请求,则肯定与路由不匹配。改为发出POST请求。
答案 1 :(得分:1)
您已使用POST方法创建了路由来创建bear,但没有获取数据的路由:
filepath
这就是为什么你得到:
400无法获取/ api / bears
添加类似的内容,然后重试。
final String filepath= "my/path/to/file.txt"; // or "file:///my/path/to/file.txt";
final URI uri = new URI(filepath);
final Path path;
if(uri.getScheme()!=null) {
path = Paths.get(uri);
}else {
path = Paths.get(filepath);
}
try (BufferedReader reader = Files.newBufferedReader(path)){
System.out.println("First line : "+reader.readLine());
}