我正在尝试从Swift到Node.js服务器执行简单的http发布请求。当我运行以下代码时,主体似乎空着。我已经尝试了几种变体,但没有成功。
客户:SWIFT 5。
func api_post(){
struct User: Codable {
let username: String
let password: String
}
let user = User(username: "ausername",password: "apassword")
guard let uploadData = try? JSONEncoder().encode(user) else {
return
}
let session = URLSession.shared
let url = URL(string: "http://XXX.XXX.XXX.XXX:XXXX/post")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = uploadData
let task = session.uploadTask(with: request, from: uploadData) { data, response, error in
if let error = error {
print ("ERROR: \(error)")
return
}
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print ("SERVER ERROR")
return
}
if let mimeType = response.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("RETURNED DATA: \(dataString)")
}
}
task.resume()
}
结果:
POST!
{}
将CURL放入相同的url确实可以正常工作:
curl -d "username=ausername&password=apassword" -X POST http://XXX.XXX.XXX.XXX:XXX/post
结果:
FROM SERVER: POST RESPONSE [OK]
服务器:NodeJ和ExpressJ。
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const port = XXXX
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/post', function (req, res) {
console.log("POST!");
var data = JSON.stringify(req.body,null,2);
console.log(data)
res.send ("FROM SERVER: POST RESPONSE [OK]");
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
我已经从Swift的文档中复制并粘贴了很多内容,但仍然无法正常工作。我会怀疑我的服务器代码,但是curl确实可以工作。所以我不确定是什么问题。
谢谢!
答案 0 :(得分:0)
最后想通了。问题出在服务器端。添加此行使其起作用。 (bp是NPM bodyParser)
app.use(bp.json()); // support json encoded bodies
现在的结果符合预期:
POST!
{ username: 'ausername', password: 'a password' }