Developing Novel API Service 1.0 with Express

The 1.0 technology stack uses Express-Generator, Express, Request, Morgan, and file-stream-rotator. Interface with chase book artifact API. At present, the interface design has home page, novel details page, search, novel article list page, ranking API.

Github creates a repository

Start by creating a repository for your files

git clone https://github.com/lanpangzhi/novel-api.git
Copy the code

Install Express-Generator to quickly generate projects

npm install -g express-generator
Copy the code

Then execute it in the directory above the previous clone repository

express --no-view novel-api
cd novel-api
npm install 
npm install request file-stream-rotator -S
// Linux MacOS
DEBUG=novel-api:* & npm start
// windows 
set DEBUG=novel-api:* & npm start
Copy the code

Generate good directory structures and files

Set cORS across domains

Open the project root directory app.js and place it above the route.

app.all(The '*'.function (req, res, next) {
    res.header("Access-Control-Allow-Origin"."*");
    res.header("Access-Control-Allow-Headers"."Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By".'3.2.1')
    res.header("Content-Type"."application/json; charset=utf-8");
    next()
});
Copy the code

Logs are written to a local file

Splitting logs by time and writing them to local disk requires the introduction of fs and file-stream-rotator modules in the app.js file.

let fs = require('fs'); 
let FileStreamRotator = require('file-stream-rotator'); Var app = express(); The followinglet logDir = path.join(__dirname, 'log'); // Check whether it existslogDir这个目录没有则创建
fs.existsSync(logDir) || fs.mkdirSync(logDir); // Log split streamlet accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD',
    filename: path.join(logDir, 'access-%DATE%.log'),
    frequency: 'daily',
    verbose: false}); // Middleware app.use(logger()'combined', { stream: accessLogStream }));
Copy the code

Creating a public file

Create a common folder in your project root directory and create a common.json file inside it

{
    "API": "http://api.zhuishushenqi.com"."PIC": "http://statics.zhuishushenqi.com"."CHAPTER": "http://chapter2.zhuishushenqi.com"
}
Copy the code

API domain name: http://api.zhuishushenqi.com image domain name: http://statics.zhuishushenqi.com section domain name: http://chapter2.zhuishushenqi.com

The home page interface

The 1.0 home page interface directly returns the top 20 hottest entries. Modify the app.js file routing middleware configuration

app.use('/index', indexRouter);
Copy the code

Modify the routes/index.js file

let express = require('express');
let request = require('request');
let common = require('.. /common/common.json'); // Reference public filesletrouter = express.Router(); / * * home page data after book list of hottest Top100 list http://api.zhuishushenqi.com/ranking/ to obtain a single {rankingId} * / router. Get ('/'.function(req, res, next) {// Request. Get ('${common.API}/ranking/54d42d92321052167dfb75e3`, function (error, response, body) {
    if (error){
      res.send(JSON.stringify({"flag": 0."msg": "Request error..."})); Parse (body) = json.parse (body);if (body.ok){
      let books = body.ranking.books.slice(0, 19);
      books.forEach(element => {
        element.cover = common.PIC + element.cover;
      });

      res.send(JSON.stringify({ "flag": 1, "books": books, "msg": "OK" }));
    }else{
      res.send(JSON.stringify({ "flag": 0."msg": "There is a problem with rankingId"})); }}); }); module.exports = router;Copy the code

Visit http://localhost:3000/index can see the data returned.

Search interface

The 1.0 search interface only retrieves the first 40 items of data, which can be queried fuzzily. Modify the app.js file routing middleware configuration, delete users.

let searchRouter = require('./routes/search');
app.use('/search', searchRouter);
Copy the code

Then delete users.js under routes folder and create search.js

let express = require('express');
let request = require('request');
let common = require('.. /common/common.json'); // Reference public filesletrouter = express.Router(); / * * fuzzy search interface Return before 40 fuzzy search data http://api.zhuishushenqi.com/book/fuzzy-search?query= {name} * / router. Get ('/'.function(req, res, next) {// Check whether the query argument has been passedif(req.query.query){// req.query.query encodes escapelet query = encodeURIComponent(req.query.query);
    request.get(`${common.API}/book/fuzzy-search? query=${query}`, function (error, response, body) {
      if (error){
        res.send(JSON.stringify({ "flag": 0."msg": "Request error..."})); } // Parse returns data body = json.parse (body);if (body.ok){
        if (body.books.length == 0){
          res.send(JSON.stringify({ "flag": 0."msg": "No books, try another name."})); } // take the first 40 and add the image URL linklet books = body.books.slice(0, 39);
        books.forEach(element => {
          element.cover = common.PIC + element.cover;
        });

        res.send(JSON.stringify({ "flag": 1, "books": books, "msg": "OK" }));
      }else{
        res.send(JSON.stringify({ "flag": 0."msg": "Request error..."})); }}); }else{
    res.send(JSON.stringify({"flag": 0."msg": "Please pass in the Query parameter"})); }}); module.exports = router;Copy the code

Go to http://localhost:3000/search/? Query = You can see the returned data in the sky.

If you like, you can send a star to Github. Thank you

My blog and GitHub address

github.com/lanpangzhi

blog.langpz.com

reference

Github.com/expressjs/m… Juejin. Cn/post / 684490… Github.com/jianhui1012…