I myself am a beginner, but the task is necessary, unfortunately there is no Russian documentation. Made API for video tutorial. Everything works, but how to check the data? I can’t put it in my head, for example, before inserting a product to check for example a password hash or to check that it belongs to another api object, help please I beg)) Or at least where to dig so that you could write logic? I attach the code:

server.js

// Dependecies var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); // MongoDb mongoose.connect('mongodb://localhost/rest_test'); // Express var app = express(); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); // Routes app.use('/api', require('./routes/api')); // Start server app.listen(3000); console.log('API is running on port 3000'); 

api.js

 // Dependencies var express = require('express'); var router = express(); // Models var Product = require('../models/product'); // Routes Product.methods(['get','put','post','delete']); Product.register(router, '/products'); // Return router module.exports = router; 

product.js

 // Dependecies var restful = require('node-restful'); var mongoose = restful.mongoose; //Schema var productSchema = new mongoose.Schema({ name: String, sku: String, price: Number }); //Return model module.exports = restful.model('Products', productSchema); 

    1 answer 1

    express is responsible for handling routes, body-parser parses the request body, mongoose deals with MongoDB, only node-restful remains.

    It has two functions in the API, before and after , defined on the model (in your Product object), they accept the HTTP method ( "get" , "post" , etc.) and the express handler .

    In the handlers, all the usual Express rules are valid: if the request processing should end there, then it is necessary to send an answer from it ( res.status(400).send("Ошибка") ?), And if you can continue, you should call next(); .

    The node-restful documentation describes what needs to be changed in req to change the stored data in before , and how to change the answer for the user in after .

    • That is, for example, to check the hash, I have to write like this? Product.methods (['get', 'put', 'post', 'delete']) .before ('post', validhash); function validhash (req, res, next) {var hash = 123; if (req.body.hash === 123) {next (); } else {res.status (400) .send ("Error"); }} - Sdafs Fasafs
    • @SdafsFasafs approximately. - D-side
    • if you know please tell me how to get the available data in the api in the script? - Sdafs Fasafs
    • @SdafsFasafs for queries in the database is used by Mongoose, and its documentation should be looked at . - D-side
    • one
      @SdafsFasafs before you check that there are none. And anyway, will you ask me every step? Have you noticed that the video lesson taught you nothing at all ? :) - D-side