1

Hi then I have a problem like this: I have an application written in swift that sends values ​​with a json array to node.js! Should I extrapolate the Username and Password parameters? how can I do?

Swift Code:

// 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 Code:

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

Log of Body:

enter image description here

New JavaScript Code Image:

enter image description here

3
  • 1
    Not really an expert in swift, but you should probably fix the swift request, rather than trying to extract the data within the server Commented Dec 28, 2017 at 15:07
  • The request body should look like {"username":"blah", password:"blahblah"} Commented Dec 28, 2017 at 15:08
  • @Malice For work reasons I am forced to use this mode to proceed! However, the same swift code I have used several times with php and I have never had problems, but at the moment I am forced to use node.js and I do not know how to solve! Commented Dec 28, 2017 at 15:12

4 Answers 4

1

Why using JSON.stringify on a string, remove it and your code should work:

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

Sign up to request clarification or add additional context in comments.

Comments

1

Change extended to false and try this one and you will get json object in request body.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Comments

1

To extend to @edkeveked,

var data = JSON.parse(Object.keys(request.body)[0]);
var username = data.Username;
var password = data.Password;

5 Comments

I had already tried this type of solution but he always writes me undefined
could you try printing data
if i print data, i have: {"Password":"orere","Username":"prov"}
Looks like you have quotes in the key, You will need to retrieve it using data['"Password"'] or something
1

The output of :

console.log(request.body);

is

{{"username": "something", "password": "somethingElse"}: ""}

You can change the form of the data to something you can easily access like this one :

{"Username": "something", "Password": "somethingElse"}

But, if for some reasons, you prefer to stick to the way the data is sent in your question, you can extract your user credentials with:

 var data = JSON.parse(Object.keys(request.body)[0]);
 var username = data.Username;
 var password = data.Password;

10 Comments

I tried with the code you told me but I print this error: TypeError: Object.key is not a function ......
It's Object.keys
I replaced the key with the keys, but when I print the username and password values ​​it tells me: undefined
You will need to JSON.parse(data), No ?
@edkeveked then I tried to use the new code but keep writing me undefined!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.