web:javascript:nodejs:api
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
web:javascript:nodejs:api [2015/04/08 07:23] – créée sgariepy | web: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:// | ||
+ | * [[https:// | ||
+ | * [[https:// | ||
+ | |||
+ | |||
+ | |||
====== 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(' | ||
+ | var Schema = mongoose.Schema; | ||
+ | var bcrypt = require(' | ||
+ | |||
+ | // 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(' | ||
+ | var user = this; | ||
+ | |||
+ | // hash the password only if the password has been changed or user is new | ||
+ | if (!user.isModified(' | ||
+ | |||
+ | // generate the hash | ||
+ | bcrypt.hash(user.password, | ||
+ | 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, | ||
+ | }; | ||
+ | // return the model | ||
+ | module.exports = mongoose.model(' | ||
+ | </ | ||
<code javascript> | <code javascript> |
web/javascript/nodejs/api.1428470595.txt.gz · Dernière modification : 2022/02/02 00:43 (modification externe)