编程知识 cdmana.com

Hide one's glory: painless implementation of local mock of front-end project with nginx + Express

Since using single page applications (SPA) Popular , about web Front end projects -- Whether it's currently based on webpack Project , It's still there grunt/gulp For projects , The basic development process is as follows :

  1. use npm start Wait for the development time environment to start , Automatically monitor source file changes and hot update browser
  2. Rely on the data returned by the back-end interface to render page logic , Or submit structured data to the back-end interface
  3. Complete phased or full development , Deploy in various ways

Among them , The best expression of “ Fore and aft end separation ” The characteristic is the second 2 Step , Compared with the traditional direct transmission HTML, Instead of lightweight parts JSON signal communication .

But from another point of view , In the development process , The dependence of the front end on the back end is, to some extent, tighter and heavier . Many times when the back-end interface service fails , Or not yet developed , Front end developers will immediately face the dilemma of cooking without rice .

“ Cutaway ” Always in a commotion ,“CRUD boy” But there is no fear ️

you 're right , What this article is going to talk about is mock Data problems .

Several common self built mock The method of data is as follows :

  1. By the enterprise / The organization builds its own special mock Site , Developers can automatically maintain the analog interface and control the return value
  2. utilize web In public mock Website
  3. install mockjs Third parties rely on packages , Write fake data in code according to its convention
  4. Hard code the custom fake data directly in the business source code

To a certain extent, the above methods can temporarily meet the development needs , But they all need to be hard coded in the project , Some have to be annotated or deleted over and over again , There is even the possibility of leaking business data . So unless it's a business / Team development specification requirements , Otherwise, it's not the most convenient way .

use express Wedge local mock

In some previous projects , I have practiced such a scheme :

such programme A It's not bad , Take advantage of a local extra boot express service ( Can be found in npm scripts neutralization dev Integrate into one command ),“ Intercept ” Some requests to live asynchronously , At the same time, it can also let go of local unfulfilled requests , Achieve targeted mock Development , You don't have to rewrite all the interfaces at the same time , In autonomous control and “ formal ” Balance and flexibility between interfaces .

But it's a little troublesome to change the project , It's an adhesive modification of the original structure , If the new project is built from scratch with the corresponding scaffold, it's OK , For retrofitting existing projects 、 For all kinds of temporary projects , It's still a bit of a brain burn and trouble every time you configure it like this ; Another small problem is , For more complex requests , Its forward It is also difficult to guarantee complete robustness of the steps .

use nginx Forward local mock

From this we developed programme B It's right programme A Improvement , It is also the method discussed in this paper . The idea is simpler and more direct , That's with nginx, To achieve a completely noninvasive mock Shell development :

The main configuration method is as follows .

nginx.conf

Make sure that the machine is installed with nginx after , stay nginx.conf Configure the related local request path in location:

#user  nobody;
events {
    worker_connections  1024;
}

http {
    resolver 8.8.8.8;
    default_type  application/octet-stream;
    sendfile      on;
    keepalive_timeout  65;
    server {
        listen       8081;
        # hosts  Make the corresponding settings in  127.0.0.1 localhost.foo.com
        server_name  localhost.foo.com;
        charset	     UTF-8;

        location / {
            proxy_pass http://localhost.foo.com:8080;
        }

		#  Route to proxy 
        location /foo-api/bar {
            proxy_set_header Host $host;
            # express  Service address 
            proxy_pass http://localhost:8090;
        }
		
        # ...  Several similar configurations of agents 
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
 Copy code 

mock.server.js

use express Write local mock service :

const express = require('express')
const bodyParser = require('body-parser')
const walk = require('klaw-sync')
const ON_DEATH = require('death')
const { execSync } = require('child_process')

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0 // eslint-disable-line

const app = express()
app.use(
  bodyParser.urlencoded({
    extended: false
  })
)
app.use(bodyParser.json())
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', argsMap.mockorigin || '*')
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, hci-secret-key, x-api-key'
  )
  res.header('Access-Control-Allow-Methods', 'POST, OPTIONS, GET')
  res.header('Access-Control-Allow-Credentials', true)
  next()
})

//  Traverse  xxx.api.js  file 
walk(__dirname)
  .filter(p => /\.api\.js$/.test(p.path))
  .map(p => p.path)
  .forEach(part => require(part)(app))

const p1 = 8090
const h1 = 'localhost'
const server = app.listen(p1, h1, () => {
  console.log(`\n\n Local server running at: http://${h1}:${p1} \n\n`)
})

//  Make sure to stop all services on exit 
ON_DEATH((signal, err) => {
  server.close()
  try {
    execSync('nginx -s stop')
  } catch (ex) {}
  console.log(signal, 'nginx has stopped.')
})
 Copy code 

Some of them in the same catalog xxx.api.js:

module.exports = function(app) {
  app.post("/foo-api/bar/query", (req, res) => {
    res.json({
      code: 1,
      msg: null,
      data: [0, 1, 3],
    });
  });
};
 Copy code 

package.json And start command

Finally, configure the corresponding npm scripts that will do :

"startlocal": "shell-exec \"npm run start --local\" \"npm run express\"",
"express": "nodemon mock/mock.server.js",
 Copy code 
  • use nginx -c <nginx.conf Absolute path > && npm run startlocal replace npm start Start development services
  • express The boot file is the same as that in the directory < Module name >.api.js Files will be added automatically mock In service
  • In the browser , The page that will automatically open url in 8080 Part to 8081 that will do


--End--

See more front-end articles
Please search Cloud front end or fewelife Official account

Reprint please indicate the source

版权声明
本文为[Chinese date]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152607774M.html

Scroll to Top