用node的express框架寫一個接口服務


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM