P
P
Polina Titova2020-10-31 16:58:51
Express.js
Polina Titova, 2020-10-31 16:58:51

How to fix a bug with RestClient API?

We create a new ad, via post in this way:

POST http://localhost:3000/api/offers HTTP/1.1
Content-Type: application/json

{
 "category": ["Разное"],
 "description": "При покупке с меня бесплатная доставка в черте города.",
 "picture": "item03.jpg",
 "title": "Продам новую приставку Sony Playstation 5.",
 "type": "offer",
 "sum": 42698
}


Added additional data validation:
const { HttpCode } = require(`../constants`);

const offerKeys = [`category`, `description`, `picture`, `title`, `type`, `sum`];

module.exports = (req, res, next) => {
  const newOffer = req.body;
  const keys = Object.keys(newOffer);
  const keysExists = offerKeys.every((key) => keys.includes(key));

  if (!keysExists) {
    res.status(HttpCode.BAD_REQUEST)
      .send(`Bad request`);
  }

  next();
};


The code is written in visual studio code, restclient apiinstalled as an extension. After starting the server without errors, I click on send request, and the following message is displayed:

HTTP/1.1 400 Bad Request
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 1059
Date: Sat, 31 Oct 2020 13:08:22 GMT
Connection: close


There is this error in the console:
SyntaxError: Unexpected token  in JSON at position 2

It turns out that the condition is met if (!keysExists), but why, if the data is the same, and how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Polina Titova, 2020-11-02
@poly-titova

The problem was that before the JSON strings there were not spaces, but some other characters (blank). The editor did not emphasize, so she did not pay attention:

{
 "category": ["Разное"],
 "description": "При покупке с меня бесплатная доставка в черте города.",
 "picture": "item03.jpg",
 "title": "Продам новую приставку Sony Playstation 5.",
 "type": "offer",
 "sum": 42698
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question