在Node.js中从Swift接收POST请求

时间:2017-07-18 07:14:29

标签: ios node.js swift http post

我正在尝试接收并处理从我的iOS应用程序发送到我的Node.js Web服务器的POST请求。每当我尝试发送此POST请求时,服务器都会响应HTTP错误502。你能看一下下面我的代码,看看它有什么问题吗?谢谢!

Node.js代码

app.post('/applogin', function(req, res) {
   var parsedBody = JSON.parse(req.body);
   console.log(parsedBody)
});


Swift Code(POST功能)

func httpPost(jsonData: Data) {
    if !jsonData.isEmpty {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData

        URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in
            NSLog("open tasks: \(openTasks)")
        }

        let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in
            NSLog("\(response)")
        })
        task.resume()
    }
    }


Swift Code(发送POST请求)

@IBAction func onClick(_ sender: Any) {
    let username = Username.text
    let password = Password.text

    var dataString = "username: \(username), password: \(password)"

    let data = dataString.data(using: .utf8)

 httpPost(jsonData: data!)

}


提前谢谢!

3 个答案:

答案 0 :(得分:2)

你必须发送一个json而不是dataString,你必须设置"内容类型"带有值的标题" application / json"

Swift 2

let request = NSMutableURLRequest(URL: requestUrl)
        request.HTTPMethod = "POST"

let params = ["username" : username, "password" : password] as Dictionary<String, AnyObject>

 request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)

request.addValue("application/json", forHTTPHeaderField: "Content-Type")

答案 1 :(得分:0)

试试这个:

app.post('/applogin', function(req, res) {
   var parsedBody = JSON.parse(req.body);
   console.log(parsedBody)
   res.send("Request received")
});

答案 2 :(得分:0)

许多回答他们没有提到我们需要在发送到后端之前为Swift端的请求设置标头,否则它将是格式错误的字符串,我们不能使用JSON.parse,这是我想出的内容(注意重要的一行):

let json = [
            "email": emailTextField.text
        ]

        let jsonData = try! JSONSerialization.data(withJSONObject: json)

        let url = URL(string: BASE_URL + "/auth/register")!

        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        // insert json data to the request
        request.httpBody = jsonData

        //IMPORTANT
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON)
            }
        }

        task.resume()

在带有Express的NodeJS中,只需调用req.body,就可以完成