为什么邮递员不识别“ /:id”而是抛出错误?

时间:2019-11-14 08:10:23

标签: node.js postgresql

我设法将nodejs与postgresql连接起来。我的问题是,当试图检索,删除或更新单个项目时,邮递员无法识别url'/ v1 /:id'。它抛出一个无法获取,或者无法删除或更新错误。但是,检索所有用户项效果很好。我不应该使用任何ORM而是纯SQL。我也检查了互联网上的所有地方,没有适当的解决方案或对此的解释。可能是什么问题?

//here is my app.js file
const express = require('express');
const bodyParser = require('body-parser');
const pg = require('pg');
const route = require('./routes/user');
const app = express();

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

app.use('/v1',route)

module.exports = app;

//here is my controller file that handles the logic
const db = require('../db/config');



const getAllUsers = (req,res,next)=> {

	db.query('select * from users',(err,result)=>{
		if(err) {
			res.status(400).send('error in connection')
		}

		res.status(200).json(result.rows);
		console.log('this is the getusers route ')
	})
}

const getUserById = (req,res,next)=> {
	const id =parseInt(req.params.id);

	db.query('select * from users where id=$1',[id],(err,results)=>{
		if(err) {
			throw err
		}
		res.status(200).send(results.rows);
		console.log('successfully found id');
	})
}

//delete item

const removeItem = (req,res,next)=> {
	const id = parseInt(req.params.id);

	db.query('DELETE from users where id=$1',[id],function(err,result){
		if(err) {
			throw err
		}
		console.log('item deleted');
	})
}

module.exports = {getAllUsers,getUserById,removeItem}

//and here is my route file that handles all the routes
const express = require('express');
const router = express.Router();
const controller = require('../controller/user');



router.get('/',controller.getAllUsers);
router.get('/users/:id',controller.getUserById);
router.delete('/item/:id',controller.removeItem);


module.exports = router;

enter image description here

3 个答案:

答案 0 :(得分:0)

:id应该被当作URL参数

http://localhost:8000/v1/users/1234->其中1234是您的:id

我在测试中使用POST

enter image description here

答案 1 :(得分:0)

enter image description here

id参数为空,请在此处输入“ id”

答案 2 :(得分:0)

在邮递员的屏幕快照中,好像您错过了在路径变量下设置“ id”的值。