let express = require('express');
let app =express();
let bodyParser = require('body-parser');
//設置跨域訪問
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://test.test.com:8080');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.header('Content-Type', 'application/json;charset=utf-8');
next()
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); //data參數以字典格式傳輸
app.post('/register',(req, res)=>{
console.log(req.body); // 打印一個對象 ,例如:{name:'zs',age:'12'}
res.send(req.body); // 不能發送數字,只能發字符串
});
app.get('/api/user', (req, res) => {
res.send("get請求正常");
});
//配置服務端口
var server = app.listen(8000, () => {
console.log("node接口服務正常運行");
});
需要安裝node,執行npm install express -save、npm install body-parser -D
