I am trying to make an HTTP POST request using an iOS Swift app to an Express.js server. In the post request, I send JSON data, creating the JSON object using a dict and SwiftyJSON. However, the request continues to time out. I think it has something to do with 'body-parser', which is what I am using to parse the HTTP body. Here is my swift code:

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

    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)
    }
}

And here is the code I use in my express.js router:

这是我在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();
});

});

If anybody could help me out and help this POST request succeed, I would greatly appreciate it. Thanks!

如果有人可以帮助我并帮助这个POST请求成功,我将不胜感激。谢谢!

1 个解决方案

#1


1

It doesn't look like you're sending back an HTTP 200 on success of your route - you only handle an error. Add a res.end(); at the end of your route (probably in the callback from the DB call) and try again.

看起来你在路由成功时发回的是HTTP 200 - 你只会处理错误。添加res.end();在你的路线的尽头(可能是在DB调用的回调中)并再试一次。

更多相关文章

  1. 这些年,我收集的JavaScript代码(二)
  2. 确保代码在*之后执行*对监视属性的更改已在UI中生效
  3. 如何在Node中创建可重用的函数而不编写样板代码
  4. arcgis api for js入门开发系列十 自定义Navigation控件样式风格
  5. 五十行javascript代码实现简单的双向数据绑定
  6. 在内容可编辑DIV中的选定文本周围包装bb代码
  7. 常用验证JS代码基础及实例
  8. 试着在我的javascript代码中理解“this”(一件事有效,另一件没有)
  9. 代码点火-如何从控制器返回Json响应

随机推荐

  1. 代码详解Python多线程、多进程、协程
  2. 【决战西二旗】|理解STL Map使用和原理
  3. 【决战西二旗】|理解STL vector原理
  4. 当我们走出三本的大门,现实给我们上了一课
  5. Android网络请求框架AsyncHttpClient (an
  6. 动画:面试官问我插入排序和冒泡排序哪个更
  7. COVID-19每日数据|04-06
  8. COVID-19每日数据|04-08
  9. Android: 八种燃爆了的菜单效果
  10. 超好看的弦图,Python一行代码就能做