使用node.js搭建一个简单的后台服务

如题,使用node.js为前端搭建一个简易型的后台服务

var http=require('http');
// 创建服务器
http.createServer(function(req,res){
  var postData="";
  // 允许跨域访问
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); 
  req.setEncoding('utf8');
  res.writeHead(200, {'Content-Type': 'application/json'});
  req.on('data',function(chunk){
         postData+=chunk;
  });
  req.on('end',function(){
       res.end(postData);
     });
  }).listen(3000);
console.log("服务启动。。。")

值得注意的是,跨域问题需要在回应函数中添加 res.setHeader('Access-Control-Allow-Origin', '*');以允许跨域访问该服务器。

原文地址:https://www.cnblogs.com/pfr-blog/p/7217783.html