Project background

Nodejs project, WebPack, wrapped with AXIos request, Promise, Nunjucks template engine;

The Nunjucks template has been shared by the front and back ends through webpack packaging strategy.

At present, network request and data processing need to be encapsulated into service module;

Directory division:

As shown above:

Put common code into service to integrate some network requests and data processing at both ends (node first screen, client requests data update again, etc.)

There are two problems here:

  1. Node module uses module.exports while webpack uses import/export.

  2. We used Promise to do two levels of encapsulation (service encapsulation, fetch encapsulation in Service: smoothen the environment difference between Node and client)

First, webpack also provides the module.exports method, so modules on both sides can be shared.

For the second problem, we used Promise and also introduced babel-polyfill globally in Webpack, but it gave an error:

Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
Copy the code

Module. Exports went bankrupt.

The solution

But in the end we solved the problem by introducing ES6-Promise:

service/fetch.js:

var axios = require('axios');
var Promise = require('es6-promise').Promise;

module.exports = function(opts, request) {
  return new Promise(function(resolve, reject) {
    axios(opts).then(function(res) {
      res = res.data
      if (res.success) {
        resolve(res)
      } else {
        reject({ ___req: opts, ___res: res })
      }
    }).catch(function(err) {
      reject({ ___req: opts, ___res: err.data || err.stack || err })
    })
  })
}
Copy the code

service/wawa.js:

var fetch = require('./fetch');
var Promise = require('es6-promise').Promise;

var getGamelist = function(params, req) {
  return new Promise(function(resolve, reject) {
    fetch({
      url: '/api/appeal/appealJoinOrderPage'.type: 'get'.params: params
    }).then(function(res) {
      resolve(res.data)
    }).catch(function(err) {
      reject(err)
    })
  })
}

module.exports = {
  getGamelist
}
Copy the code

And we also tried to introduce ES6-Promise globally, still reporting errors;

Module.exports: : native Promise syntax This can only be circumvented by introducing es6-Promise into the current JS.

Fortunately, the repeated introduction of ES6-Promise in each JS will be de-weighted when the final WebPack is packaged, avoiding the problem of larger packages.

At this point, the solution shared by the front-end and back-end codes of Node passes. In addition, you can also write common code other than service, which improves reusability and maintainability.