Outils pour utilisateurs

Outils du site


web:javascript:nodejs:api

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Prochaine révision
Révision précédente
web:javascript:nodejs:api [2015/04/08 07:23] – créée sgariepyweb:javascript:nodejs:api [2022/02/02 00:42] (Version actuelle) – modification externe 127.0.0.1
Ligne 1: Ligne 1:
 +====== Faire un API en NodeJS ======
 +
 +
 +
 +
 +
 +====== Resources ======
 +
 +  * [[https://blog.risingstack.com/10-best-practices-for-writing-node-js-rest-apis/|10 Best Practices for Writing Node.js REST APIs]]
 +  * [[https://github.com/abhishekbanthia/Public-APIs|Public APIs]]
 +  * [[https://stormpath.com/blog/the-problem-with-api-authentication-in-express|The Problem with API Authentication in Express]]
 +
 +
 +
 ====== Exemple d'un API simple ====== ====== Exemple d'un API simple ======
  
 +<code javascript>
 +// grab the packages that we need for the user model
 +var mongoose = require('mongoose');
 +var Schema = mongoose.Schema;
 +var bcrypt = require('bcrypt-nodejs');
 +
 +// user schema
 +var UserSchema = new Schema({
 +    name: String,
 +    username: { type: String, required: true, index: { unique: true }},
 +    password: { type: String, required: true, select: false }
 +});
 +
 +// hash the password before the user is saved
 +UserSchema.pre('save', function(next) {
 +    var user = this;
 +
 +    // hash the password only if the password has been changed or user is new
 +    if (!user.isModified('password')) return next();
 +
 +    // generate the hash
 +    bcrypt.hash(user.password, null, null, function(err, hash) {
 +        if (err) return next(err);
 +
 +        // change the password to the hashed version
 +        user.password = hash;
 +        next();
 +    });
 +});
 +
 +// method to compare a given password with the database hash
 +UserSchema.methods.comparePassword = function(password) {
 +    var user = this;
 +    return bcrypt.compareSync(password, user.password);
 +};
  
 +// return the model
 +module.exports = mongoose.model('User', UserSchema);
 +</code>
  
 <code javascript> <code javascript>
web/javascript/nodejs/api.1428470595.txt.gz · Dernière modification : 2022/02/02 00:43 (modification externe)