Node服務器搭建
01.安裝Express模塊
- cd 到指定目錄下,例如
D:\程序代碼\NodeServer - 執(zhí)行cmd:
cnpm install express --save
02.安裝其他解析模塊
- 執(zhí)行cmd:
cnpm install body-parser --save - 執(zhí)行cmd:
cnpm install cookie-parser --save - 執(zhí)行cmd:
cnpm install multer --save
03.創(chuàng)建服務腳本處理對應URL
- 創(chuàng)建
Server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("應用實例,訪問地址為 http://%s:%s", host, port)
})
- 解析某個請求并返回json
app.get('/extras', function (req, res) {
console.log("獲取Extra列表");
// 輸出 JSON 格式
//處理跨域
res.header("Access-Control-Allow-Origin", "*");
var response = {
"success":true,
"data":[
{ "imgUrl": '', "title": '標題1', "content":'內(nèi)容1', "count":1, "id":1 },
{ "imgUrl": '', "title": '標題2', "content":'內(nèi)容2', "count":2, "id":2 },
{ "imgUrl": '', "title": '標題3', "content":'內(nèi)容3', "count":3, "id":3 },
]
};
console.log(response);
res.send(JSON.stringify(response));
});
04.處理跨域請求
由于本地調(diào)試從一個端口訪問另一個端口涉及到跨域的問題,所以在服務端取消跨域設(shè)置
- 在具體一個請求下面增加如下代碼
res.header("Access-Control-Allow-Origin", "*");
05.開啟服務
執(zhí)行cmd:node Server.js