user7538827
user7538827

Reputation:

parse string value to an Object

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

Upvotes: 1

Views: 261

Answers (4)

edkeveked
edkeveked

Reputation: 18381

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;

Upvotes: 1

Malice
Malice

Reputation: 1482

To extend to @edkeveked,

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

Upvotes: 1

YouneL
YouneL

Reputation: 8361

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

Upvotes: 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 }));

Upvotes: 1

Related Questions