引入和初始化
const express = require('express')
const app = express()
使用
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
引入
var bodyParser = require('body-parser')
使用
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json 解析json数据
app.use(bodyParser.json())
引入
request = require('request');
put请求
var rand = Math.floor(Math.random()*100000000).toString();
request(
{ method: 'PUT',
uri: 'http://mikeal.iriscouch.com/testjs/' + rand,
multipart:
[ { 'content-type': 'application/json',
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
},
{ body: 'I am an attachment' }
]
},
function (error, response, body) {
if(response.statusCode == 201){
console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
} else {
console.log('error: '+ response.statusCode)
console.log(body)
}
})
get请求
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
)
.on('data', function(data) {
// decompressed data as it is received
console.log('decoded chunk: ' + data)
})
.on('response', function(response) {
// unmodified http.IncomingMessage object
response.on('data', function(data) {
// compressed data as it is received
console.log('received ' + data.length + ' bytes of compressed data')
})
})
引入:
const morgan = require('morgan')
使用:
// log only 4xx and 5xx responses to console
app.use(morgan('dev', {//开发者模式下,仅4|5开头的日志
skip: function (req, res) { return res.statusCode < 400 }
}))
// log all requests to access.log
app.use(morgan('common', {
stream: fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
}))
app.get('/', function (req, res) {
res.send('hello, world!')
})
引入:
const mysql= require('mysql');
使用单次连接
var connection = mysql.createConnection({
host: 'example.org',
user: 'bob',
password: 'secret'
});
connection.connect(function (err) {
//错误处理
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
//没有错误执行的内容
console.log('connected as id ' + connection.threadId);
});
或者也可以这样
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
使用连接池进行连接
var pool = mysql.createPool({
connectionLimit: 10,
host: 'example.org',
user: 'bob',
password: 'secret',
database: 'my_db'
});
pool.query(sql, function (error, results, fields) {
if (error) throw error;
console.log('The results is: ', results);
});
参数及方法说明:
方法:createPool: 创建一个连接池
connectionLimit:最大连接数
host:需要连接的主机名
user:连接数据库的用户名
password:user 对应得数据库登陆密码
database: 连接的数据库
方法:query:执行查询
sql:执行的 sql 语句
error:错误信息
results: 包含查询结果
fields: 包含有关返回结果字段的信息(如果有)
更多模块示例可以参考这里npmjs