Configuring the Node Server

After you have purchased the server, use Xshell to connect to the server.

1, install,nvm

The curl - o - https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash or wget -- qO https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bashCopy the code

Once installed, close and restart Xshell.

2. Install node using NVM

// Check the current version of node that can be installed. NVM ls-remote'nodejs.org'NVM install v10.16.0 // The installation is complete. The default node version is v10.16.0. NPM version 6.9.0 Now Using Node V10.16.0 (NPM v6.9.0) Creating Defaultalias: NVM install v10.11.0 default -> v10.16.0 // You can use the command to check the version of node --version // NVM can install multiple node versions NVM install v10.11.0 // You can use the command to check how many node versions NVM ls is installed // The default node version can be specified using commands. If multiple node versions are installed, be sure to specify a default NVM versionaliasDefault v10.11.0 // If you don't want to use the default, just use it at zero hours, you can use the command NVM use v10.11.0Copy the code

3. Install nginx

$cat /etc/redhat-release // install epel-release source yum install epel-release -y The/etc/yum. Repos. D/nginx. Repo / / in the configuration Settings nginx installation source, specific can consult nginx website document ('http://nginx.org/en/linux_packages.html#stable'Name =) [nginx] nginx repo baseurl=http://nginx.org/packages/centos/7/$basearch/ gpgCheck =0 enabled=1 // install nginx yum install nginx -y // Check whether the nginx installation is successful, whereis nginx is displayedCopy the code

4. Set nginx

// Start systemctlenableNginx // Start the service, restart yes'systemctl restart nginx'And stop is'stop'Systemctl start nginx // reload the service, because you do not want to restart the service after reconfiguration. Systemctl status nginx // If the firewall is enabled on CentOS7, Firewall-cmd --zone=public --permanent --add-service= HTTP sudo firewall-cmd --reload firewall-cmd --list-service // Network access permissions must be enabled for CentOS7 to use reverse proxy setsebool httpD_can_network_connect 1Copy the code

5. Deploy the test project

// create folder mkdir server // go to foldercdServer // create js file vim home.js // write test code, note that the IP address must be set to 0.0.0.0, if set to 127.0.0.1, the port 3000 is not connected const HTTP = require('http');

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type'.'text/plain');
  res.end('Hello World\n'); }); Server.listen (port, hostname, () => {console.log(' the server is running in http://${hostname}:${port}/ `); }); // Start node home.js // If an error occurs'Unhandled 'error' event', the likelihood is port was being used, check the port usage ps - ef | grep node / / if you have, delete,'xxxx'for'root'After the number skill -9 XXXXXCopy the code

If the server is running at http://0.0.0.0:3000/, the Node is running successfully. After the server is running successfully, log in to ali Cloud and configure security group rules

If the configuration is successful, the following information is displayed:

Allows a user-defined TCP 3000/3000 IPv4 address segment to access 0.0.0.0/0 node background portCopy the code

Enter the public IP address of the server in the address box of the browser and add 3000. If Hello World is displayed, the security group is successfully configured

6. Configure nginx

/ / to enter'/etc/nginx'Folder, check it out'nginx.conf'The configuration filecd/etc/nginx ls vim nginx.conf // Nginx of an earlier version'nginx.conf'The folder contains the following contents //# include /etc/nginx/conf.d/*.conf;
// # include /etc/nginx/sites-enabled/*;/ / removeThe '#'// Create an nginx configuration file with an arbitrary name. I like to use the project name and port number, for example'wxServer-3000'Vim/etc/nginx/conf. D/wxServer - 3000. The conf/code/write configuration files# Project name
upstream wxServer {
    The node port number required for the proxy is the same as the port number you wroteServer 0.0.0.0:3000;# nginx maximum number of connections
    keepalive 8;
}

# nginx server instance
server {
    The default port number is Http port 80. If you want to configure other ports, you need to change SELinux SettingsListen 0.0.0.0:80;Enter the domain name or IP address to be accessed by others. Separate multiple domain names or IP addresses with Spaces
    server_name lzf.fun www.lzf.fun;
    Error log address
    access_log /var/log/nginx/wxServer-3000.log;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
      [upstream] [upstream] [upstream] [upstream] [upstreamproxy_pass http://wxServer/; proxy_redirect off; Nginx: the configuration file /etc/nginx/nginx.conf syntax is ok: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok: configuration file /etc/nginx/nginx.conftest// Open the security group for port 80 in the background of Ali cloud, then enter the domain name in the browser, you can see'Hello World'Nginx configuration is successfulCopy the code

7. Configure PM2

// Install PM2 NPM install PM2 -gpwdIt's your folder pathcd pwd// Start pm2, --watch, every time the code changes automatically start, -i 1 start an instance, according to the server and several core Settings // -I 0 will automatically start as many processes according to the current number of cores // for security and performance consideration, Pm2 start home.js --watch -i 1 // check pm2 pm2 ls // check pm2 logs // check pm2 restart home.js // stop Id by looking for pm2 stop home | id / / delete pm2 delete home | id / / understand the details of the process pm2 go home | id / / close Xshell, refresh the domain name, you can also see'Hello World'The configuration is successful.Copy the code

Using transpilers with PM2 and NodeJS to use Babel for ES6 and PM2

Interface configuration for linking wechat public accounts

8. Write local Node code

const Koa = require('koa')
const cors = require('koa2-cors')
const Router = require('koa-router')
const crypto = require('crypto')

const app = new Koa()

// 微信配置
const config = {
  wechat: {
    appID: 'appID',
    appsecret: 'appsecret',
    token: 'Maya'Use (cors({origin: CTX => {origin: CTX => {origin: CTX => {origin: CTX => {origin: CTX => {origin: CTX => {if (ctx.url === '/test') {
        return false
      }
      return The '*'
    },
    exposeHeaders: ['WWW-Authenticate'.'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET'.'POST'.'DELETE'],
    allowHeaders: ['Content-Type'.'Authorization'.'Accept'})) // New Router() wxserver.get ()'/', async ctx => {
  const { signature, timestamp, nonce, echostr } = ctx.query
  const token = config.wechat.token
  let hash = crypto.createHash('sha1')
  const arr = [token, timestamp, nonce].sort()
  hash.update(arr.join(' '))
  const shasum = hash.digest('hex')
  if (shasum === signature) {
    return (ctx.body = echostr)
  }
  ctx.status = 401
  ctx.body = 'Invalid signature'Const router = new router () router.use()'/forWx', wxServer.routes(), Wxserver.allowedmethods ()) // Load middleware app.use(router.routes()).use(router.allowedMethods()) app.listen(3000) console.log('[demo] start-quick is starting at port 3000')

Copy the code

9. Test whether the local code is ok through Intranet penetration

1. Use localtunnel to enable Intranet penetration. It is not recommended

NPM install -g localtunnel // enable local server lt --port 3000Copy the code

2. It takes some time to configure Intranet penetration through NatApp

You can use the Intranet penetration tool NatApp! This article installs configuration,

If you code to turn on port 3000, you’d better configure port 3000 as well

If you see a message indicating that the tunnel connection is successful but the 127.0.0.1:3000 port connection fails, it does not mean that the installation and configuration failed, but you need to start the code

After the installation and configuration is successful, start

node home.js
Copy the code

If Invalid Signature is displayed on the browser, the Intranet is successfully penetrated

10. Open a wechat public platform test account

In the wechat public platform test management page, interface configuration information, URL fill in your natApp startup domain name plus forWx, for example, my domain name is

http://qf7rja.natappfree.cc/forWx
Copy the code

The Token is your own custom, you can write whatever you want, but it has to be the same as the Token in your native code, so I’m using Maya

Click Submit, the configuration is successful

11. Interface configuration for the server to link to the wechat public number

Through the above test account, verify that the code is no problem, can configure the interface configuration, the rest is to upload the code to the server, choose RZ and SZ installation, of course, XFTP is better

// Install yum install LRZSZ -y // upload, execute command, select package file rz // download, filename is your package server folder, or a single file sz filenameCopy the code

Once the upload is successful, unzip it, clean up the Hello World code, empty PM2, and re-attach the current code to PM2

Enter domain name + forWx in the browser. If Invalid signature is displayed, the configuration fails. Locate the cause

Log in to the wechat public platform, choose Basic Configuration -> Server Configuration, and then configure the test account according to the configuration method

Click Submit, the configuration is successful

The end of the

Hiss ~~~ long breath, study for a long time, node server finally configuration success, and has been linked to the public number interface configuration, and I still have a test account

You can use a test account to write code locally and then upload it to the server for verification

The reason for doing so is that the test account is not distressed to play bad, and then a good server to play bad, configuration can be troublesome

What’s left is to develop the specific business, access to AccessToken, auto-reply to messages, custom menus, etc.

reference

# Nginx node.js + Nginx reverse proxy # Nginx # Nginx Access the wechat official account