用node的express框架寫一個介面服務
阿新 • • 發佈:2020-07-23
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