gpt4 book ai didi

javascript - Express 路由器不适用于发布请求

转载 作者:行者123 更新时间:2023-11-30 12:17:01 25 4
gpt4 key购买 nike

我正在着手处理整个 MEAN Stack。我正在整理一个小型测试/初学者应用程序来学习基础知识。我目前正在尝试使用不同路线的快速路由器。我在使路由正常工作时遇到了一些问题。

当我转到 localhost:8000/api 时,它工作正常。但是当我尝试访问 localhost:8000/api/users 时,它返回一个 404 错误 :(

这是我的代码

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var port = process.env.PORT || 8000;
var User = require('./app/models/user');

mongoose.connect('mongodb://localhost:27017/ApiDataBase');

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.use(function(req, res, next)
{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, \
22 Authorization');
next();
});

app.use(morgan('dev'));

// testing if express runs

app.get('/', function(req, res) {
res.send('Welcome to this awesome site!');
});

// creating new instance of the router

var apiRouter = express.Router();

apiRouter.use(function(req, res, next){

console.log('Somebody came to vist');

next();
});

// testing the router

apiRouter.get('/', function(req, res) {
res.json({ message: 'WWWUUUUHHÚÚÚ Welcome!'});
});

// I'm not getting this part to work

apiRouter.route('/users')

.post(function(req, res) {

var user = new User();

user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;

user.save(function(err) {
if(err){

if(err.code == 11000)
return res.json({ success: false, message: 'Þessi notandi er þegar til'});
else
return res.send(err);
}

res.json({ message: 'Notandi stofanður'});
});


})

app.use('/api', apiRouter);

app.listen(8000);
console.log('Magic happens on port' + port);

最佳答案

when I try to access localhost:8000/api/users it returns a 404 error

你没有到 localhost:8000/api/usersGET 路由,你有一个到它的 POST 路由:

apiRouter.route('/users')

.post(function(req, res) {

也就是说,当你向localhost:8000/api/users发送一个GET请求时,express找不到路由,因为你它不存在.您应该针对 POST 请求对其进行测试。

关于javascript - Express 路由器不适用于发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32171627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com