Express JS无法PUT / DELETE

时间:2016-01-29 12:16:37

标签: javascript node.js express

项目结构

.app.js
.routes/
....resources.js

我运行了以下服务器实例:

app.js

"use strict";
const app = require('express')();
const resources = require('./routes/resources');

app.use('/', resources);

const server = app.listen('3000', () => {
  let host = server.address().address;
  host = (host == '::' ? 'localhost' : host);
  const port = server.address().port;
  // log it
  console.log('listening at http://%s:%s', host, port);
});

我有GET和POST请求正常工作(routes / resources.js),即

"use strict"
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
//parser
router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// data
let resources = [{
  id: 1,
  name: 'Foo'
}];

// POST
router.post('/resources', (req, res) => {
  let item = req.body;
  //send status
  if (!item.id) {
    return res.sendStatus(500);
  }
  // saved as a string, id must be int
  item.id = parseInt(item.id, 10);
  // add id
  resources.push(item);
  // send the response of new resource
  res.send('/resources/' + parseInt(item.id, 10));
});

使用Postman我可以成功发布,但是下面的PUT和DELETE 给我无法删除/资源/ 消息:

// PUT
router.put('/resources/:id', (req, res) => {
  // get id from request
  let id = parseInt(req.body.id, 10);
  // find existing id in resources
  let existingItem = resources.filter(r => r.id === id)[0];
  // if it doesn't exist
  if(!existingItem) {
    let item = req.body;
    item.id = id;
    resources.push(item);
    res.setHeader('Location', '/resources/' + id);
    res.sendStatus(201)
  } else {
    existingItem.name = req.body.name;
    res.sendStatus(204);
  }
});
// DELETE
router.delete('/resources/:id', (req, res) => {
  let id = parseInt(req.body.id, 10);
  let existingItem = resources.filter(r => r.id === id)[0];

  if (!existingItem) {
    return res.sendStatus(404)
  }
  resources = resources.filter(r => r.id !== id);
  res.sendStatus(204)
});

尽管可能是答案正在盯着我,但为什么会这样。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

Doh,我给了DELETE和PUT路径/:id参数

router.delete('/resources/:id...)

router.put('/resources/:id'...)

当我只是将DELETE / PUT请求指向POSTMAN内的' / resources /时。

感谢@Molda的帮助 - 让我意识到自己的错误!