2017-05-27 36 views
0

我正在尝试使用iOS Swift应用程序向Express.js服务器发出HTTP POST请求。在发布请求中,我发送JSON数据,使用dict和SwiftyJSON创建JSON对象。但是,请求继续超时。我认为它与'body-parser'有关,这是我用来解析HTTP正文的。这里是我的SWIFT代码:具有iOS Swift请求时序输出的Express.js服务器

override func viewDidLoad() { 
    super.viewDidLoad() 


    var dict = ["name": "FirstChannel", "verified": 0, "private": 1, "handle": "firstChannel", "subscribers": 0] as [String : Any] 
    var jsonData = JSON(dict) 

    do { 
     let post:NSData = try jsonData.rawData() as NSData 
     var postLength: NSString = String(post.length) as NSString 
     var url = URL(string: "http://10.0.0.220:3000/channel/createChannel")! 
     var request = NSMutableURLRequest(url: url) 
     request.httpMethod = "POST" 
     request.httpBody = post as Data 
     request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") 
     request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.setValue("application/json", forHTTPHeaderField: "Accept") 

     NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler: { (resposne, data, error) in 
      if(error != nil) { 
       print(error) 
      } 
      else { 
       print(data) 
      } 
     }) 



    } 
    catch { 
     print(error.localizedDescription) 
    } 
} 

这里是代码我在express.js路由器使用:

var express = require('express'); 
var router = express.Router(); 
var http = require('http'); 
var url = require('url'); 
var util = require('util'); 
var bodyParser = require('body-parser') 
var ObjectID = require('mongodb').ObjectID; 

router.use(bodyParser.json()); 
router.use(bodyParser.urlencoded({extended: true})); 

var mongoose = require('mongoose'); 
mongoose.connect('mongodb://localhost/my_db'); 

var channelSchema = mongoose.Schema({ 
    name: String, 
    verified: String, 
    private: String, 
    channelID: String, 
    handle: String, 
    subscribers: String 
}); 

var Channel = mongoose.model("Channel", channelSchema); 
router.post('/createChannel', bodyParser, function(req, res, next) { 
    req.body = true; 
    if(!req.body) return res.sendStatus(400); 
    var objID = new ObjectID(); 

    var newChannel = new Channel({ 
     name: req.body["name"], 
     verified: req.body["verified"], 
     private: req.body["private"], 
     channelID: objID, 
     handle: req.body["handle"], 
     subscribers: (req.body["subscribers"]) 
    }); 

newChannel.save(function(err, point){ 
    if(err) console.log(err); 
    else res.end(); 
}); 

}); 

如果有人可以帮助我,帮助这个POST请求成功,我将不胜欣赏它。谢谢!

回答

1

您的路线成功后,您看起来并不像您送回HTTP 200 - 您只能处理错误。在路线末端添加一个res.end();(可能在数据库调用的回调中)并重试。

+0

嗨,谢谢你的回复。我加了res.end();在DB保存调用结束时,但请求仍超时。任何其他想法? –

+0

你对我的回应是空的是正确的。我还需要发送在我的数据库保存回调中声明的点对象。 –

相关问题