nodejs写接口
在项目根目录下:“npm init” 初始化nodejs项目,生成package.json文件
npm install express -S (安装express框架)
在根目录下新建文件app.js
var express = require('express');//引入express模块
var app = express();
//定义方法
app.get('/',function(req,res){
res.send('HellowWorld')
});
//定义端口,此处所用为3000端口,可自行更改
var server = app.listen(3000,function(){
console.log('runing 3000...');
})
创建接口响应路径 (get)
var express = require('express');//引入express模块
var app = express();
//定义方法
app.get('/',function(req,res){
res.send('HellowWorld')
});
//响应接口
app.get('/list/product',function(req,res){
//数据
let result={
err:0,
msg:'ok',
data:{
"name":"huawei",
"price":"1999",
"title":"huawei huawei huawei",
"id":"1"
}
}
res.send(result)
})
//定义端口,此处所用为3000端口,可自行更改
var server = app.listen(3000,function(){
console.log('runing 3000...');
})
运行命令 node .\app.js 启动项目
在浏览器中输入 http://127.0.0.1:3000/list/product 即可看到数据
发送post请求
// 1.导入http模块
var http = require('http');
// 2. 发送请求
var post_data = JSON.stringify({
'width':100,
'height':100
}) // post所需要传递的数据
var options = {
hostname:'www.baidu.com', //此处不能写协议,如 : http://,https:// 否则会报错
port:5001,
path:'/api',
method:'POST',
headers: {
'Content-Type':'application/json',
'Content-Length': post_data.length
}
}
var req = http.request(options,function(res){
console.log('STATUS:'+res.statusCode);
var body = ''
res.setEncoding('utf8');
res.on('data',function(chunk){
body += chunk;
})
res.on('end', function(){
process.nextTick(() =>{
body = JSON.parse(body)
try{
console.log(body) // 请求到的数据
} catch (err) {
console.log('compress error', err)
}
})
})
res.on('error', function(err) {
console.log('api error', err)
})
})
// write data to request body
req.write(post_data)
req.end()
(附)案例:返回图片url给前端渲染
var express = require('express');//引入express模块
var app = express();
// 开放根目录下image文件夹,使得外网可以访问
app.use('/image',express.static('./image'));
//定义方法
app.get('/',function(req,res){
res.send('HellowWorld')
});
app.get('/home',function(req,res){
let data=[
{ 'img1': 'http://127.0.0.1:3000/image/J1.jpg'},
{ 'img2': 'http://127.0.0.1:3000/image/J2.png'},
{ 'img3': 'http://127.0.0.1:3000/image/J3.png'}
]
res.send(data)
});
//定义端口,此处所用为3000端口,可自行更改
var server = app.listen(3000,function(){
console.log('runing 3000...');
})
还没有评论,来说两句吧...