您好我有这样的问题:我有一个用swift编写的应用程序,它将带有 json 数组的值发送到 node.js !我应该推断用户名和密码参数吗?我怎么办?
Swift代码:
// prepare json data
let json: [String: Any] = ["Username": ""+UsernameTextBox.text!,"Password": ""+PasswordTextBox.text!]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://localhost:3000/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
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()
Node.js代码:
var express = require("express");
var myParser = require("body-parser");
var app = express();
//Login
app.use(myParser.urlencoded({extended : true}));
app.post("/login", function(request, response) {
console.log(request.body);
});
//Application Listen on Port
app.listen(3000,function(){
console.log("Application Server Start on Port: 3000");
})
身体记录:
新的JavaScript代码图片:
答案 0 :(得分:1)
输出:
console.log(request.body);
是
{{"username": "something", "password": "somethingElse"}: ""}
您可以将数据的格式更改为您可以轻松访问的内容,如下所示:
{"Username": "something", "Password": "somethingElse"}
但是,如果出于某些原因,您更愿意坚持在问题中发送数据的方式,则可以使用以下方式提取用户凭据:
var data = JSON.parse(Object.keys(request.body)[0]);
var username = data.Username;
var password = data.Password;
答案 1 :(得分:1)
将扩展名更改为false并尝试此操作,您将在请求正文中获取json对象。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
答案 2 :(得分:1)
扩展到@edkeveked,
"/(i(?:phone|pad|pod)) OS (\d+_\d+_\d+)/i"
答案 3 :(得分:1)
为什么在字符串上使用JSON.stringify
,删除它并且您的代码应该有效:
var data = JSON.parse(Object.keys(request.body)[0]);
var username = data.Username;
var password = data.Password;
var body = {'{"Password":"dsdsd","Username":"dsdsdsds"}':''};
var data = JSON.parse(Object.keys(body)[0]);
var username = data.Username;
var password = data.Password;
console.log(username, password);