[转]ionic项目之上传下载数据

本文转自:http://blog.csdn.net/superjunjin/article/details/44158567

一,首先是上传数据

记得在angularjs的controller中注入$http依赖

  1. var data = {id: $scope.task_id,   
  2.             groupId: $scope.task_groupid,   
  3.             importance: $scope.priority_level,   
  4.             classname:$scope.classname,   
  5.             title: $scope.task_title,   
  6.             date: $scope.todo_date,   
  7.             detail: $scope.task_detail,  
  8.             images:$scope.images_list,  
  9.             name:$scope.name,  
  10.             record:$scope.recordPath,  
  11.             donedate:$scope.done_date}  
  12.           
  13.          $http({  
  14.             method: 'POST',  
  15.             url: 'http://localhost:3000',  
  16.             params:{  
  17.                 'require': data  
  18.             }  
  19.               
  20.          }).success(function(data,status,headers,config){  
  21.               
  22.          }).error(function(data,status,headers,config){  
  23.               
  24.          });  
var data = {id: $scope.task_id, 
         	groupId: $scope.task_groupid, 
         	importance: $scope.priority_level, 
         	classname:$scope.classname, 
         	title: $scope.task_title, 
         	date: $scope.todo_date, 
         	detail: $scope.task_detail,
         	images:$scope.images_list,
         	name:$scope.name,
         	record:$scope.recordPath,
         	donedate:$scope.done_date}
        
         $http({
         	method: 'POST',
         	url: 'http://localhost:3000',
         	params:{
         		'require': data
         	}
         	
         }).success(function(data,status,headers,config){
         	
         }).error(function(data,status,headers,config){
         	
         });

$http方法中的data参数,服务端没有接收成功

$http方法中的params参数,服务端接收成功

服务端接收方法是 url.parse(req.url, true).query.params

(params即是加在url?后的参数)

二,然后是下载数据

  1.     //刷新  
  2.     $scope.refresh = function(){  
  3.         $http.get("http://localhost:3000/refresh")  
  4.         .success(function(data, status, headers, config) {  
  5.         // this callback will be called asynchronously  
  6.         // when the response is available  
  7.           
  8.         alert("success");  
  9.         alert("["+data.substring(0,data.lastIndexOf(","))+"]");                                                                                                                                                                                                                                                                    
  10.         TodoListService.deleteAndAddTask(JSON.parse("["+data.substring(0,data.lastIndexOf(","))+"]"));  
  11.         TodoListService.findByGroupId($stateParams.groupId).then(function(todolists) {  
  12.          
  13.             $scope.todolists = todolists; //对应类别的所有数据list  
  14.         });  
  15.           
  16.         })  
  17.         .error(function(data, status, headers, config) {  
  18.         // called asynchronously if an error occurs  
  19.         // or server returns response with an error status.  
  20.         alert("error "+data);  
  21.   
  22.         });  
  23.           
  24.           
  25. //      .success(function(response) {  
  26. //  
  27. //          console.log(response);  
  28. //          alert(response);  
  29. //      });  
  30.              
  31.     }  
    //刷新
    $scope.refresh = function(){
    	$http.get("http://localhost:3000/refresh")
    	.success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        
        alert("success");
        alert("["+data.substring(0,data.lastIndexOf(","))+"]");                                                                                                                                                                                                                                                                  
        TodoListService.deleteAndAddTask(JSON.parse("["+data.substring(0,data.lastIndexOf(","))+"]"));
        TodoListService.findByGroupId($stateParams.groupId).then(function(todolists) {
       
			$scope.todolists = todolists; //对应类别的所有数据list
		});
        
        })
    	.error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("error "+data);

        });
    	
    	
//      .success(function(response) {
//
//          console.log(response);
//          alert(response);
//      });
           
    }

回调的success方法中返回的data数据,即为服务器response给客户端的数据

注意:返回的json字符串要保证符合json格式(一开始最外层没加中括号就会报错)

三,服务端代码

  1. var http = require('http');  
  2. var url = require('url');  
  3. var util = require('util');  
  4. var fs = require('fs');   
  5.   
  6. http.createServer(function(req, res){  
  7.     var urldata = req.url+"";  
  8.     var require;  
  9.     console.log('connet');  
  10.     if(urldata.substring(1) == "refresh")  
  11.     {  
  12.        console.log("refresh");  
  13.        require = "";  
  14.        fs.readFile('writefile.txt','utf8', function(err, data) {   
  15.         if (err) {   
  16.           console.error(err);   
  17.         } else {   
  18.           console.log(data);   
  19.           
  20.           res.end(data+"");  
  21.         }   
  22.        });  
  23.          
  24.     }  
  25.     else  
  26.     {  
  27.        console.log("add");  
  28.        require = url.parse(req.url, true).query.require+",";  
  29.        fs.open('writefile.txt', 'a', function opend(err, fd) {   
  30.        if(err) {   
  31.            console.error(err);   
  32.            return;   
  33.        }   
  34.        var writeBuffer = new Buffer(require),  
  35.            bufferPosition = 0,  
  36.            bufferLength = writeBuffer.length,  
  37.            filePosition = null;  
  38.        fs.write(fd,  
  39.              writeBuffer,  
  40.              bufferPosition,  
  41.              bufferLength,  
  42.              filePosition,  
  43.              function wrote(err,written){  
  44.                if(err){throw err;}  
  45.                //console.log(err);  
  46.              });  
  47.        });  
  48.     }  
  49.       
  50.   
  51. }).listen(3000);  
var http = require('http');
var url = require('url');
var util = require('util');
var fs = require('fs'); 

http.createServer(function(req, res){
	var urldata = req.url+"";
    var require;
	console.log('connet');
	if(urldata.substring(1) == "refresh")
	{
       console.log("refresh");
	   require = "";
	   fs.readFile('writefile.txt','utf8', function(err, data) { 
	    if (err) { 
		  console.error(err); 
	    } else { 
		  console.log(data); 
		
          res.end(data+"");
	    } 
       });
       
	}
	else
	{
	   console.log("add");
       require = url.parse(req.url, true).query.require+",";
	   fs.open('writefile.txt', 'a', function opend(err, fd) { 
	   if(err) { 
		   console.error(err); 
		   return; 
	   } 
	   var writeBuffer = new Buffer(require),
		   bufferPosition = 0,
		   bufferLength = writeBuffer.length,
		   filePosition = null;
	   fs.write(fd,
		     writeBuffer,
		     bufferPosition,
		     bufferLength,
		     filePosition,
		     function wrote(err,written){
	           if(err){throw err;}
			   //console.log(err);
			 });
       });
	}
	

}).listen(3000);

还有个问题

由于ionic有自己的服务用于启动项目,它启动了http://localhost:8100 的服务,而ionic项目访问服务器需要另外的端口

所以在电脑浏览器调试时会报错

 XMLHttpRequest cannot load http://localhost:3000/refresh. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

需要让浏览器忽略跨域问题就行了,可以干脆关闭所有安全策略,当然浏览器会提示你稳定性和安全性降低

如果不想每次启动都用命令行,也可以把启动参数添加到浏览器快捷方式里:右键点击Chrome图标,在“快捷方法”标签页的“目标”一栏添加启动参数到末尾即可(先留一个空格)

项目地址(包括ionic项目和简易node服务器代码,服务器代码只用到了server.js和writefile.txt)

http://download.csdn.net/detail/superjunjin/8487079

原项目来自于http://rensanning.iteye.com/blog/2072034

原文地址:https://www.cnblogs.com/freeliver54/p/4990453.html