Nginx NodeJS Express Mysql Restful Summary

 

 

 

1. install node.js + nginx + pm2

see http://www.cnblogs.com/avcs/articles/7412599.html
mkdir -p /opt/node
mkdir -p /opt/nginx
download and install node.js + nginx + pm2

nginx.config


#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
error_log logs/error.log error;

pid logs/nginx.pid;


events {
worker_connections 1024;
}


http {
include mime.types;
default_type application/octet-stream;

#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;

server {
listen 9090;
server_name avatar-back.appmagics.cn;

listen 55443 ssl;
listen [::]:55443 ssl;

ssl on;

# replace this with your cert+key path
ssl_certificate /opt/nginx/ssl/nginx-crt.pem;
ssl_certificate_key /opt/nginx/ssl/nginx-key.pem;

# ssl_verify_client on;
# ssl_verify_depth 2;

ssl_session_timeout 1d;
ssl_session_cache shared:SSL:20m;
ssl_session_tickets off;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK';

ssl_stapling on;
ssl_stapling_verify on;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
index index.html index.htm;
}

location /test {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

location /rest {
proxy_pass http://127.0.0.1:8088;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

location /todo {
proxy_pass http://127.0.0.1:8088;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}


# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}


# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;

# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;

# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;

# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
#}

}

2. install express + mysql

see http://www.cnblogs.com/avcs/articles/7416696.html


mkdir -p /home/ubuntu/NodeRest
cd /home/ubuntu/NodeRest
npm init --yes
$ npm install express --save
$ npm install mysql --save
$ npm install body-parser --save
package.json generated

create server.js as following

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mysql = require('mysql');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'magics',
password: 'appmagics',
database: 'magicsdb'
});

// connect to database
mc.connect();

// default route
app.get('/rest', function (req, res) {
return res.send({ error: true, message: 'hello' })
});

// Retrieve all todos
app.get('/todos', function (req, res) {
mc.query('SELECT * FROM tasks', function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos list.' });
});
});

// Search for todos with ‘bug’ in their name
app.get('/todos/search/:keyword', function (req, res) {
let keyword = req.params.keyword;
mc.query("SELECT * FROM tasks WHERE task LIKE ? ", ['%' + keyword + '%'], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Todos search list.' });
});
});

// Retrieve todo with id
app.get('/todo/:id', function (req, res) {

let task_id = req.params.id;

if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}

mc.query('SELECT * FROM tasks where id=?', task_id, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results[0], message: 'Todos list.' });
});

});

// Add a new todo
app.post('/todo', function (req, res) {

let task = req.body.task;

if (!task) {
return res.status(400).send({ error:true, message: 'Please provide task' });
}

mc.query("INSERT INTO tasks SET ? ", { task: task }, function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'New task has been created successfully.' });
});
});

// Update todo with id
app.put('/todo', function (req, res) {

let task_id = req.body.task_id;
let task = req.body.task;

if (!task_id || !task) {
return res.status(400).send({ error: task, message: 'Please provide task and task_id' });
}

mc.query("UPDATE tasks SET task = ? WHERE id = ?", [task, task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});

// Delete todo
app.delete('/todo', function (req, res) {

let task_id = req.body.task_id;

if (!task_id) {
return res.status(400).send({ error: true, message: 'Please provide task_id' });
}
mc.query('DELETE FROM tasks WHERE id = ?', [task_id], function (error, results, fields) {
if (error) throw error;
return res.send({ error: false, data: results, message: 'Task has been updated successfully.' });
});
});

// all other requests redirect to 404
app.all("*", function (req, res, next) {
return res.send('page not found');
next();
});

// port must be set to 8080 because incoming http requests are routed from port 80 to port 8080
app.listen(8088, function () {
console.log('Node app is running on port 8088');
});

// allows "grunt dev" to create a development server with livereload
module.exports = app;

3. run server.js
start nginx

cd /home/ubuntu/NodeRest
pm2 start server.js

4. http test
http://avatar-back.appmagics.cn:9090/rest

5. http authentication
see http://www.cnblogs.com/avcs/articles/7419286.html

npm install http-auth
npm install -g htdigest

var http = require("http");
var auth = require("http-auth");
var basic = auth({
authRealm: "Private area",
authFile: __dirname + "/htpasswd",
authType: "basic"
});
var server = http.createServer(function(request, response) {
basic.apply(request, response, function(username) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello " + username);
response.end();
});
});

server.listen(80);
console.log("Server is listening");

var http = require("http");
var auth = require("http-auth");
var digest = auth({
authRealm: "Private area",
authFile: __dirname + "/htpasswd",
authType: "digest"
});
var server = http.createServer(function(request, response) {
digest.apply(request, response, function(username) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello " + username);
response.end();
});
});

server.listen(80);
console.log("Server is listening");

posted on 2017-08-23 17:32  fanbird2008  阅读(52)  评论(0编辑  收藏  举报

导航