Categories
JavaScript Answers

How to get the path from the request with Node.js?

Sometimes, we want to get the path from the request with Node.js.

In this article, we’ll look at how to get the path from the request with Node.js.

How to get the path from the request with Node.js?

To get the path from the request with Node.js, we can use the request.url property.

For instance, we write

const http = require("http");
const url = require("url");

const start = () => {
  const onRequest = (request, response) => {
    const { pathname } = url.parse(request.url);
    console.log(pathname);
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("Hello World");
    response.end();
  };
  http.createServer(onRequest).listen(8888);
};

start();

to get the request.url from the request.

Then we call url.parse to parse it to return an object with the pathname to get the request URL path.

Conclusion

To get the path from the request with Node.js, we can use the request.url property.

Categories
JavaScript Answers

How to configure axios to use SSL certificate?

Sometimes, we want to configure axios to use SSL certificate.

In this article, we’ll look at how to configure axios to use SSL certificate.

How to configure axios to use SSL certificate?

To configure axios to use SSL certificate, we set the rejectUnauthorized option to false and add our certificate files as the options for axios.

For instance, we write

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
  cert: fs.readFileSync("./usercert.pem"),
  key: fs.readFileSync("./key.pem"),
  passphrase: "YYY",
});

axios.get(url, { httpsAgent });

to create the httpsAgent object with the https.Agent constructor.

We set rejectUnauthorized to disable client verification.

And then we add the certificate and private keys by setting the files as the values of cert and key respectively.

We also set the passphrase for the certificate if we have one.

Then we call axios.get or other request methods with httpsAgent in the option object.

We can also create a new axios instance with the httpsAgent with

const instance = axios.create({ httpsAgent });

Conclusion

To configure axios to use SSL certificate, we set the rejectUnauthorized option to false and add our certificate files as the options for axios.

Categories
JavaScript Answers

How to create a Node.js server that accepts POST requests?

Sometimes, we want to create a Node.js server that accepts POST requests.

In this article, we’ll look at how to create a Node.js server that accepts POST requests.

How to create a Node.js server that accepts POST requests?

To create a Node.js server that accepts POST requests, we can use the http module.

For instance, we write

const http = require("http");
const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "textplain" });
  if (request.method === "GET") {
    response.end("received GET request.");
  } else if (request.method === "POST") {
    response.end("received POST request.");
  } else {
    response.end("Undefined request .");
  }
});

server.listen(8000);
console.log("Server running on port 8000");

to call http.createServer with a callback to create a web server.

We call it with a callback that receives the request.

If request.method is 'POST', then a POST request is received.

And then we call response.end to return a response body string.

Conclusion

To create a Node.js server that accepts POST requests, we can use the http module.

Categories
JavaScript Answers

How to use the Mongoose use of select method in Node.js?

Sometimes, we want to use the Mongoose use of select method in Node.js.

In this article, we’ll look at how to use the Mongoose use of select method in Node.js.

How to use the Mongoose use of select method in Node.js?

To use the Mongoose use of select method in Node.js, we can use the find method with the fields we want to return in the results.

For instance, we write

User.find({}, "first last", (err, user) => {
  //...
});

to call User.find with 'first last' to get the User results and return the first and last properties in each result only.

We get the returned query results from the user parameter.

Conclusion

To use the Mongoose use of select method in Node.js, we can use the find method with the fields we want to return in the results.

Categories
JavaScript Answers

How to hash password with Mongoose?

Sometimes, we want to hash password with Mongoose.

In this article, we’ll look at how to hash password with Mongoose.

How to hash password with Mongoose?

To hash password with Mongoose, we can use bcrypt.

For instance, we write

const mongoose = require("mongoose");
const { Schema } = mongoose;
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;

const UserSchema = new Schema({
  username: { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true },
});

UserSchema.pre("save", function (next) {
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(this.password, salt, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      next();
    });
  });
});

UserSchema.methods.comparePassword = (candidatePassword, cb) => {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    if (err) {
      return cb(err);
    }
    cb(null, isMatch);
  });
};

module.exports = mongoose.model("User", UserSchema);

to create the User schema with the password field.

When we save the User entry, we call bcrypt.getSalt to generate the salt.

In the genSalt callback, we call bcrypt.hash to hash the password with the salt created.

And then we set this.password to hash and call next to save.

Then we create the comparePassword method by setting UserSchema.methods.comparePassword to a function that calls bcrypt.compare with the candidatePssword and this.password which is current password saved.

We call the cb callback that we call comparePassword with in the function and get whether both passwords match with isMatch.

Then we use it by writing

const testUser = new User({
  username: "abc",
  password: "password123",
});

testUser.save((err) => {
  if (err) throw err;
});

User.findOne({ username: "abc" }, (err, user) => {
  if (err) throw err;

  user.comparePassword("password123", (err, isMatch) => {
    if (err) throw err;
    console.log("password123:", isMatch);
  });

  user.comparePassword("abc", (err, isMatch) => {
    if (err) throw err;
    console.log("abc:", isMatch);
  });
});

to create the testUser User.

And then we call findOneto find the user withusernameset to‘abc’`.

In the findOne callback, we call comparePassword to compare valid and invalid passwords respectively and get whether they match the saved password with isMatch.

Conclusion

To hash password with Mongoose, we can use bcrypt.