工具:安装node;
1,创建文件夹 server,
2 ,在server文件夹下分别创建server.js 和 package.json 文件
3,server.js 代码:
var express = require('express');
var app=express(); app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
//res.header("Content-Type", "text/plain;charset=utf-8");
//res.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
next();
}); var bodyParser = require('body-parser'); app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // get请求地址: localhost:3000
app.get('/',function(req,res){
res.send('首页');
// res.json({"msg":'get请求成功!'});
}) var numb=0;
// post请求地址: localhost:3000/post
app.post('/post',function(req,res){
console.log(req.body, numb);
res.json({"msg":'post请求成功' + numb++});
}) // get请求地址: localhost:3000/jsonp
app.get('/jsonp',function(req,res){
//console.log(req.body);
res.jsonp({"msg":'这是jsonp请求'}); }) app.listen(3000,'127.0.0.1');
4, package.json代码:
{
"dependencies": {
"ejs": "^2.5.6",
"express": "^4.15.3",
"socket.io": "^2.0.3",
"body-parser": "~1.17.1"
}
}
5,打开终端cd到server文件夹目录下,运行 npm install
6, 依赖安装完成后运行 node ./server.js
7, 打开浏览器,地址栏输入localhost:3000 ; 回车页面显示 “首页” 两个字, 服务成功运行。