最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NODE JS + Postman : Cannot PATCH URL - Stack Overflow

programmeradmin3浏览0评论

Consider the code :

const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser')

// use middleware
app.use(express.json());
app.use(bodyParser.json());

const fileLocation = `${__dirname}/dev-data/data/tours-simple.json`;
const theTours = JSON.parse(fs.readFileSync(fileLocation));

app.patch('api/v1/tours/:id', (req, res) =>{
  if (req.params.id * 1 > theTours.length) {
    return res.status(404).json({
      status: 'fail',
      message: 'Invalid ID'
    });
  }

  res.status(200).json({
    status: 'success',
    data: {
      tour: '<Updated tour here ...>'
    }
  });
});

const port = 3000;
app.listen(port, () => {
  console.log(`App is running on port ${port}`);
});

When I try to PATCH from Postman the URL :

Action PATCH 
URL : 127.0.0.1:3000/api/v1/tours/3

Sending raw :

I get this :

Why is it happening ? Where did I go wrong ?

Consider the code :

const fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser')

// use middleware
app.use(express.json());
app.use(bodyParser.json());

const fileLocation = `${__dirname}/dev-data/data/tours-simple.json`;
const theTours = JSON.parse(fs.readFileSync(fileLocation));

app.patch('api/v1/tours/:id', (req, res) =>{
  if (req.params.id * 1 > theTours.length) {
    return res.status(404).json({
      status: 'fail',
      message: 'Invalid ID'
    });
  }

  res.status(200).json({
    status: 'success',
    data: {
      tour: '<Updated tour here ...>'
    }
  });
});

const port = 3000;
app.listen(port, () => {
  console.log(`App is running on port ${port}`);
});

When I try to PATCH from Postman the URL :

Action PATCH 
URL : 127.0.0.1:3000/api/v1/tours/3

Sending raw :

I get this :

Why is it happening ? Where did I go wrong ?

Share Improve this question edited Aug 31, 2019 at 9:57 JAN asked Aug 31, 2019 at 9:44 JANJAN 21.9k66 gold badges188 silver badges334 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

You are missing a slash in the route:

app.patch('/api/v1/tours/:id', (req, res) =>{

You are missing the leading / (slash) there when defining the route with

app.patch('/...', (req, res) => { 
    ... 
    ...
 });

Express needs that leading slash when defining the routes :) Hope this helps

发布评论

评论列表(0)

  1. 暂无评论