简体   繁体   中英

Express JS unable to PUT/DELETE

Project structure

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

I have the following server instance running:

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);
});

I have the GET and POST requests working (routes/resources.js) fine ie

"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));
});

Using Postman I can successfully post, however the following PUT and DELETE give me the Cannot DELETE /resources/ message:

// 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)
});

Head scratching as to why, though it may be that the answer is staring me in the face. Any help would be appreciated!

Doh, I gave the DELETE and PUT paths the /:id parameter

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

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

when I was merely pointing the DELETE / PUT requests to '/resources/ inside POSTMAN.

Thanks for the help @Molda - made me realise my mistake!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM