How to use js to write API interface on the front end?

Get into the habit of writing together! This is the 11th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

The focus of modern front-end developers' daily work is to write pages and adjust interfaces.

Many front-end developers want to expand their technology stack, learn back-end knowledge, and want to learn back-end languages ​​such as Java, Python, and even C#. In fact, using Node to implement backend services is very simple, and the next step is today's focus: Express.

What is Express

Express is the most popular Node framework and is the underlying library for many other popular Node frameworks. It provides the following mechanisms:

  1. Write handlers for requests (routes) that use different HTTP verbs in different URL paths.
  2. A "view" rendering engine is integrated to generate responses by inserting data into templates.
  3. Set common web application settings, such as the port used to connect, and where to render the response template.
  4. Add additional request processing "middleware" anywhere in the request processing pipeline.

Now start writing an API interface

The main techniques used in the following:

Node.js: JavaScript running on the server side

Express: node.js MVC framework

MongoDB: NoSQL database

1. Create a project, create related files

mkdir todoApp
cd todoApp
npm init

touch server.js
mkdir api
mkdir api/controllers api/models api/routes
touch api/controllers/taskController.js api/models/taskModel.js api/routes/taskRoutes.js
复制代码

2. Set up the database

npm install mongoose --save
复制代码

Modify api/models/taskModel.js,

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var TaskSchema = new Schema({
  name: {
    type: String,
    required: "Enter the name of the task"
  },
  Created_date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model("Tasks", TaskSchema);
复制代码

3. Set up routing

Modify api/routes/taskRoute.js

module.exports = function(app) {
  var taskList = require('../controllers/taskController');

  app.route('/tasks')
    .get(taskList.all_tasks)
    .post(taskList.create_task);


  app.route('/tasks/:taskId')
    .get(taskList.load_task)
    .put(taskList.update_task)
    .delete(taskList.delete_task);
};
复制代码

4.Controller

Modify api/controllers/taskController.js

var mongoose = require("mongoose"),
  Task = mongoose.model("Tasks");

// 查询所有
exports.all_tasks = function(req, res) {
  Task.find({}, function(err, task) {
    if (err) res.send(err);
    res.json(task);
  });
};

// 新增
exports.create_task = function(req, res) {
  var new_task = new Task(req.body);
  new_task.save(function(err, task) {
    if (err) res.send(err);
    res.json(task);
  });
};

// 根据id查询
exports.load_task = function(req, res) {
  Task.findById(req.params.taskId, function(err, task) {
    if (err) res.send(err);
    res.json(task);
  });
};

// 更新
exports.update_task = function(req, res) {
  Task.findOneAndUpdate(
    { _id: req.params.taskId },
    req.body,
    { new: true },
    function(err, task) {
      if (err) res.send(err);
      res.json(task);
    }
  );
};

// 删除
exports.delete_task = function(req, res) {
  Task.remove(
    {
      _id: req.params.taskId
    },
    function(err, task) {
      if (err) res.send(err);
      res.json({ message: "Task successfully deleted" });
    }
  );
};
复制代码

5. Create an API

npm install --save-dev nodemon
npm install express --save
复制代码

Build the API with server.js.

Modify server.js

var express = require("express"),
  app = express(),
  port = process.env.PORT || 3000,
  mongoose = require("mongoose"),
  Task = require("./api/models/taskModel"), // 加载创建的模型
  bodyParser = require("body-parser");

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/Tododb");

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var routes = require("./api/routes/taskRoutes");
routes(app); 

app.listen(port); 

console.log("todo list RESTful API server started on: " + port);
复制代码

6. Start booting

//启动数据库
mongod
//启动项目
npm run start
复制代码

7. Create complete

Access the API:

新增:POST http://localhost:3000/tasks

Get all: GET http://localhost:3000/tasks

Query by id: GET http://localhost:3000/tasks/:id

更新:PUT http://localhost:3000/tasks/:id

删除:DELETE http://localhost:3000/tasks/:id

Guess you like

Origin juejin.im/post/7085372657943707685