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請求成功,我將不勝欣賞它。謝謝!
嗨,謝謝你的回覆。我加了res.end();在DB保存調用結束時,但請求仍超時。任何其他想法? –
你對我的迴應是空的是正確的。我還需要發送在我的數據庫保存回調中聲明的點對象。 –