Configure node server
After purchasing the server, use Xshell to link to the server.
1. Install nvm
curl -o- /nvm-sh/nvm/v0.34.0/ | bash or wget -qO- /nvm-sh/nvm/v0.34.0/ | bash
After installation, close and restart Xshell.
2. Use nvm to install node
// Check the currently installed node versionnvm ls-remote // Select the ''Official website LTS stable versionnvm install v10.16.0 // This display appears to indicate that the installation is complete. The default is the node version of v10.16.0 and the npm version of 6.9.0Now using node v10.16.0 (npm v6.9.0) Creating default alias: default -> v10.16.0 // You can use the command to view the versionnode --version // nvm can install multiple node versionsnvm install v10.11.0 // You can use the command to view how many node versions are installednvm ls // You can use the command to specify the default node version. If multiple node versions are installed, you must specify a default version.nvm alias default v10.11.0 // If you don't want to use the default, just use it at zero, you can use the commandnvm use v10.11.0
3. Install nginx
// Check the server system version$ cat /etc/redhat-release // Install the epel-release sourceyum install epel-release -y // Open source configurationvim /etc// // Set up nginx installation source in configuration. For details, please refer to nginx official website documentation ('/en/linux_packages.html#stable')[nginx] name=nginx repo baseurl=/packages/centos/7/$basearch/ gpgcheck=0 enabled=1 // Install nginxyum install nginx -y // Check whether nginx is installed successfully. If successful, the path will be displayed.whereis nginx
4. Set up nginx
// Set up startupsystemctl enable nginx // Start the service, restart is 'systemctl restart nginx', stop is 'stop'systemctl start nginx // Reload, because after reconfiguration, you do not want to restart the service. You can use reload at this timesystemctl reload nginx // Check the server statussystemctl status nginx // If the CentOS7 system has a firewall turned on, you also need to open the firewall port.firewall-cmd --zone=public --permanent --add-service=http sudo firewall-cmd --reload firewall-cmd --list-service // If you want to use a reverse proxy, CentOS7 needs to turn on network accesssetsebool httpd_can_network_connect 1
5. Deploy the test project
// Create foldermkdir server // Enter the foldercd server // Create a js filevim // Write the test code, note that the IP address here must be configured to 0.0.0.0.0. If it is configured to 127.0.0.1, the external network will report an error port 3000 link that does not work.const http = require('http'); const hostname = '0.0.0.0'; const port = 3000; const server = ((req, res) => { = 200; ('Content-Type', 'text/plain'); ('Hello World\n'); }); (port, hostname, () => { (`The server runs on http://${hostname}:${port}/`); }); // start upnode // If an error 'Unhandled 'error' event' is reported, it may be that the port has been occupied. First check the port occupancy situationps -ef|grep node // If there is an occupation, delete the occupation, 'xxxx' is the number after 'root'skill -9 xxxxx
Appears: The server is running at http://0.0.0.0:3000/, which means that the node is running successfully. After the operation is successful, log in to the Alibaba Cloud background to configure security group rules.
The configuration is successful and the following is displayed:
Allow custom TCP 3000/3000 IPv4 address segment access 0.0.0.0/0 node background port
Then you can enter your server's public network IP address in the browser address bar and add: 3000. The successful appearance of Hello World means that the security group configuration is successful.
6. Configure nginx
// Enter the '/etc/nginx' folder and view the '' configuration filecd /etc/nginx ls vim // The lower version of nginx '' folder contains the following content// # include /etc/nginx//*.conf; // # include /etc/nginx/sites-enabled/*; // Remove '#' Number// Create nginx configuration file, the file name is free, I usually like to use the project name and port number, such as 'wxServer-3000'vim /etc/nginx// // Write configuration file code# Project nameupstream wxServer { # The node port number that needs the proxy, which is the port number you wroteserver 0.0.0.0:3000; # nginx maximum number of connectionskeepalive 8; } # nginx server instanceserver { # The port number that is proxyed, default port 80 of the Http protocol. If you configure other ports, you need to change the settings of SELinuxlisten 0.0.0.0:80; # The domain name or IP address visited by others, separated by spacesserver_name ; # Error log storage addressaccess_log /var/log/nginx/; 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; # proxy_pass Set the server domain name of the reverse proxy. Do not use the reverse proxy, just use the name of the upstream above.proxy_pass http://wxServer/; proxy_redirect off; } } // After saving the configuration file, check whether it is written errorsnginx -t // The following content appears is correctnginx: the configuration file /etc/nginx/ syntax is ok nginx: configuration file /etc/nginx/ test is successful // Reload nginx serversystemctl reload nginx // Open in Alibaba Cloud background80Security group for ports,Then enter the domain name in the browser,Can see 'Hello World' That meansnginxThe configuration was successful
7. Configure PM2
// Install PM2npm install pm2 -g // Enter the folder stored in your node project, pwd is your folder pathcd pwd // Start pm2, --watch listening, each code changes automatically start, -i 1 Start an instance, according to several core settings of the server// -i 0 will automatically start as many processes as possible based on the current number of cores of the machinepm2 start --watch -i 1 // View pm2pm2 ls // View error logpm2 logs // Restartpm2 restart // Stop, id is obtained by viewingpm2 stop home|id // deletepm2 delete home|id // Learn more about the programpm2 describe home|id // closureXshell,Refresh the domain name,You can also see 'Hello World' Indicates that the configuration is successful
Link to WeChat official account interface configuration
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() // WeChat configurationconst config = { wechat: { appID: 'appID', appsecret: 'appsecret', token: 'Maya' } } // Use koa2-cors to solve cross-domain problems( cors({ origin: ctx => { if ( === '/test') { return false } return '*' }, exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 5, credentials: true, allowMethods: ['GET', 'POST', 'DELETE'], allowHeaders: ['Content-Type', 'Authorization', 'Accept'] }) ) // Verified to WeChatconst wxServer = new Router() ('/', async ctx => { const { signature, timestamp, nonce, echostr } = const token = let hash = ('sha1') const arr = [token, timestamp, nonce].sort() (('')) const shasum = ('hex') if (shasum === signature) { return ( = echostr) } = 401 = 'Invalid signature' }) // Load all routesconst router = new Router() ('/forWx', (), ()) // Load routing middleware(()).use(()) (3000) ('[demo] start-quick is starting at port 3000')
9. Test whether the local code is OK through intranet penetration
1. Start intranet penetration through localtunnel. It is not recommended. It may be successful in startup, but the domain name link fails.
// Installnpm install -g localtunnel // Turn on the local serverlt --port 3000
2. It takes a little time to start intranet penetration through natapp.
Natapp can be penetrated through the intranet! This article installs configuration,
If your code is to open port 3000, it is best to configure port 3000 as well.
tips: If you see that the tunnel link is successful, but the 127.0.0.1:3000 port link fails, it does not mean that the installation configuration has failed. You need to start the code.
After the installation configuration is successful, start
node
Being able to successfully see Invalid signature on the browser means that the intranet penetration is successful
10. Open a WeChat public platform to test the account
On the WeChat public platform test management page, interface configuration information, URL fill in the domain name started by your natapp plus forWx, for example, my domain name is
/forWx
Tokens are customized by you and can be written casually, but they must be consistent with the tokens in your local code. I am using Maya here
Click Submit to display the configuration is successful
11. Server link WeChat official account interface configuration
Through the above test account, I verified that the code has no problems and can configure the interface configuration successfully. The rest is to upload the code to the server. Install it and select rz and sz. Of course, it is better to use xftp
// Installyum install lrzsz -y // Upload, execute commands, and select package filerz // Download, filename is the server folder you packaged, or a single filesz filename
After the upload is successful, decompress, clear the previous Hello World code, clear PM2, and hang the current code on PM2 again.
Enter the domain name + forWx in the browser and it will appear. Invalid signature means it will be successful. If it does not appear, the configuration will not be successful. You need to troubleshoot the reason.
Log in to your account on WeChat public platform, select Basic Configuration --> Server Configuration, and then configure it according to the configuration test account
Click Submit to display the configuration is successful
end
Shh~~~ I let out a long sigh and studied it for a long time. The node server was finally configured successfully, and it has been linked to the official account interface configuration, and I have a test account
You can use the test account to write code locally and then upload it to the server to verify it.
The reason for this is that it is not a bad idea if the test account is broken. Another one is done in a blink of an eye. The server is broken, so it will be troublesome to configure it.
The rest is to develop specific businesses, such as getting AccessToken, automatically replying to messages, custom menus, etc.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.