~~~
//引包 (核心模块)
var http = require('http');
var fs = require('fs');
// 将本地模拟的数据放在data.js中并导入
var localData = require('./data.js');
var server = http.createServer();
server.on('request', function (req, res) {
console.log(req.url);
if(req.url === '/') {
// res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Origin', 'http://192.168.22.2');
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
//JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
res.end(JSON.stringify(localData.data));
}
else if (req.url.indexOf('/images/') === 0) {
fs.readFile('.' + req.url + '.jpg', function (err, data) {
res.end(data);
})
}
});
server.listen(3030, function () {
console.log('server is running');
})
~~~