工具:安装node;
1,创建文件夹 server,
2 ,在server文件夹下分别创建server.js 和 package.json 文件
3,server.js 代码:
1 var express = require(‘express‘); 2 var app=express(); 3 4 app.all(‘*‘, function(req, res, next) { 5 res.header("Access-Control-Allow-Origin", "*"); 6 res.header("Access-Control-Allow-Headers", "X-Requested-With"); 7 res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); 8 res.header("X-Powered-By",‘ 3.2.1‘); 9 res.header("Content-Type", "application/json;charset=utf-8"); 10 //res.header("Content-Type", "text/plain;charset=utf-8"); 11 //res.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); 12 next(); 13 }); 14 15 var bodyParser = require(‘body-parser‘); 16 17 app.use(bodyParser.json()); 18 app.use(bodyParser.urlencoded({ extended: false })); 19 20 // get请求地址: localhost:3000 21 app.get(‘/‘,function(req,res){ 22 res.send(‘首页‘); 23 // res.json({"msg":‘get请求成功!‘}); 24 }) 25 26 var numb=0; 27 // post请求地址: localhost:3000/post 28 app.post(‘/post‘,function(req,res){ 29 console.log(req.body, numb); 30 res.json({"msg":‘post请求成功‘ + numb++}); 31 }) 32 33 // get请求地址: localhost:3000/jsonp 34 app.get(‘/jsonp‘,function(req,res){ 35 //console.log(req.body); 36 res.jsonp({"msg":‘这是jsonp请求‘}); 37 38 }) 39 40 app.listen(3000,‘127.0.0.1‘);
4, package.json代码:
1 { 2 "dependencies": { 3 "ejs": "^2.5.6", 4 "express": "^4.15.3", 5 "socket.io": "^2.0.3", 6 "body-parser": "~1.17.1" 7 } 8 }
5,打开终端cd到server文件夹目录下,运行 npm install
6, 依赖安装完成后运行 node ./server.js
7, 打开浏览器,地址栏输入localhost:3000 ; 回车页面显示 “首页” 两个字, 服务成功运行。
原文:https://www.cnblogs.com/zhenguo-chen/p/10447740.html