parse string value to an Object - javascript

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:
New JavaScript Code Image:

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

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

To extend to #edkeveked,
var data = JSON.parse(Object.keys(request.body)[0]);
var username = data.Username;
var password = data.Password;

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;

Related

While sending routes and data to server side from client . I'm not recieving data on server side

I'm trying to upload the file to server. currently I'm uploading images.
This is my client side code
onClickfileupload(){
let data={};
let path="";
let api_url = '/api/uploadFileFromIonicHome';
this.fileChooser.open()
.then(uri =>
{
path= JSON.stringify(uri);
alert(path);
data={
userEmail: this.userEmail,
userName: this.userName,
userRole: this.userRole,
fileComment: this.desc,
type: "file",
fullFileName:'file-'+Date.now()+'.jpg'
}
this.imagesProvider.uploadImage(path, data, api_url).then((res) => {
let dataPassedBackObj = {
reload: true,
pathOfFile: path,
typeOf: "picture",
userName: this.userName,
fileComment: this.desc
}
alert("Successfully uploaded picture...");
this.events.publish('toggleMenu');
}, err => {
alert(err.http_status);
alert("There was error in uploading picture...");
}); })
.catch(e => alert(e));
}
This is my provider what I'm using to upload the file to server side.
This is my providers code
uploadImage(img, data ,api_url) {
alert("Uploading file...");
// Destination URL
let url = SERVER_HOST + api_url;
// File for Upload
var targetPath = img;
console.log("line 28"+targetPath);
var options: FileUploadOptions = {
fileKey: 'image',
chunkedMode: false,
mimeType: 'multipart/form-data',
params: data,
};
const fileTransfer: FileTransferObject = this.transfer.create();
return fileTransfer.upload(targetPath, url, options);
}
This is my server side code where I'm getting the routes. but req. body is coming empty {}.
This is part of my server side code
app.post('/api/uploadFileFromIonicHome', uploadFromHome.single('image'), function(req, res) {
console.log('within /api/uploadFileFromIonicHome');
console.log(req.body.type);
console.log(req.body);
var userName = req.body.userName;
var userEmail = req.body.userEmail;
var userType = req.body.userRole;
var fileName = req.body.fileName;
var type = req.body.type;
var comment = req.body.comment;
var fileComment = req.body.fileComment;
I'm getting empty "req.body"
and "req.body.type is undefined."
This the error I'm getting
typeerror:cannot convert object to primitive value
Use connect-multiparty to read files. Reference link
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload', multipartMiddleware, function(req, resp) {
console.log(req.body, req.files);
// don't forget to delete all req.files when done
});

Posting data from swift to node.js

I know this has been gone over before but I've spent hours on this and can't seem to figure out how to post data to a node.js server... I've started the project using cloud9 and node.js so I know I have a good install and that I'm starting with a working site.
In swift I'm sending a post request like
func post (){
let url = URL(string: "https://the-game-stevens-apps.c9users.io/index.html/")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Accept")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "name=henry&message=HelloWorld"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
Then in my server.js file I have
var router = express();
router.use(express.urlencoded());
router.post('/index.html', function(req, res) {
var obj = {name:req.body.name,text:req.body.message};
});
I have plenty of experience with javascript but I'm a noob when it comes to node.js and have just been poking around with it, any help is really appreciated
The only part I can correct in your node.js code is
To get router you need to call express.Router();
const express = require('express');
const router = express.Router();
router.use((req,res,next) => {
console.log("/" + req.method, "host"+ req.host, "Params" + req.params);
next();
});
router.post('/index.html', (req, res) => {
const obj = {name:req.body.name,text:req.body.message};
//insert obj into database
});

Express.js Server with iOS Swift Request Timing Out

I am trying to make an HTTP POST request using an iOS Swift app to an Express.js server. In the post request, I send JSON data, creating the JSON object using a dict and SwiftyJSON. However, the request continues to time out. I think it has something to do with 'body-parser', which is what I am using to parse the HTTP body. Here is my swift code:
override func viewDidLoad() {
super.viewDidLoad()
var dict = ["name": "FirstChannel", "verified": 0, "private": 1, "handle": "firstChannel", "subscribers": 0] as [String : Any]
var jsonData = JSON(dict)
do {
let post:NSData = try jsonData.rawData() as NSData
var postLength: NSString = String(post.length) as NSString
var url = URL(string: "http://10.0.0.220:3000/channel/createChannel")!
var request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main, completionHandler: { (resposne, data, error) in
if(error != nil) {
print(error)
}
else {
print(data)
}
})
}
catch {
print(error.localizedDescription)
}
}
And here is the code I use in my express.js router:
var express = require('express');
var router = express.Router();
var http = require('http');
var url = require('url');
var util = require('util');
var bodyParser = require('body-parser')
var ObjectID = require('mongodb').ObjectID;
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended: true}));
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/my_db');
var channelSchema = mongoose.Schema({
name: String,
verified: String,
private: String,
channelID: String,
handle: String,
subscribers: String
});
var Channel = mongoose.model("Channel", channelSchema);
router.post('/createChannel', bodyParser, function(req, res, next) {
req.body = true;
if(!req.body) return res.sendStatus(400);
var objID = new ObjectID();
var newChannel = new Channel({
name: req.body["name"],
verified: req.body["verified"],
private: req.body["private"],
channelID: objID,
handle: req.body["handle"],
subscribers: (req.body["subscribers"])
});
newChannel.save(function(err, point){
if(err) console.log(err);
else res.end();
});
});
If anybody could help me out and help this POST request succeed, I would greatly appreciate it. Thanks!
It doesn't look like you're sending back an HTTP 200 on success of your route - you only handle an error. Add a res.end(); at the end of your route (probably in the callback from the DB call) and try again.

Not able to pass object with AngularJS to web backend

Title says it all. I'm new to this so I'm sure it must be a simple mistake.
Here's the controller
$scope.removeProduct = function(product){
console.log(product._id);
var inData = new Object();
inData._id = product._id;
console.log(inData);
$http({ url:"/api/deleteprod/", inData, method: "POST"
}).then(function () {
console.log("got here");
var index = $scope.vehicles.indexOf(product);
$scope.vehicles.splice(index, 1);
})
};
and here's the server side.
module.exports = function(app, mongoose, config) {
app.post('/api/deleteprod', function(req, res){
console.log("in app post",req);
var MongoClient = mongodb.MongoClient;
var url='mongodb://localhost:27017/seedsdev';
});
};
Obviously what I want is to pass the _id to the server so I can work with it, but when I output req it's about 50 pages long and has none of the info I wanted. Before it's passed the object can be seen to be fine fia console.log.
What's the rookie mistake I'm making?
When calling $http, you pass the post data with a data property. Currently you're passing an inData property. Change to this:
$http({ url:"/api/deleteprod/", data: inData, method: "POST" }).then(...)
Update:
On the server side, you'll need to make sure you have a JSON parsing middleware, like that from body-parser:
app.use(require('body-parser').json())
Once you are parsing the body using body-parser, you'll have a req.body property with the parsed JSON.
What you are missing are two below things.
1) Data in post request as suggested by #Jacob
2) A parser of Post param body-parser. //npm install body-parser --save
This will help you to parse the POST data in node js.
So code would look like
$scope.removeProduct = function(product){
console.log(product._id);
var inData = new Object();
inData._id = product._id;
console.log(inData);
$http({ url:"/api/deleteprod/", data: inData, method: "POST"
}).then(function () {
console.log("got here");
var index = $scope.vehicles.indexOf(product);
$scope.vehicles.splice(index, 1);
})
};
IN Backend
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
module.exports = function(app, mongoose, config) {
app.post('/api/deleteprod', function(req, res){
console.log("in app post",req.body._id);
var MongoClient = mongodb.MongoClient;
var url='mongodb://localhost:27017/seedsdev';
});
};

Why does my $http.post return a 400 error?

I fairly new to MEAN, so sorry if this question is so obvious. I want to send an email to a contact when they click a send button. My code for handling a send email is using a post I am currently using a SendGrid Nodejs API to send the email. The problem is I keep running into a 400 Post Error.
This is the error I get in my Google Chrome Console
This is the error I get in my server terminal
This is in my controller.js:
$scope.send = function(contact) {
console.log("Controller: Sending message to:"+ contact.email);
$http.post('/email', contact.email).then(function (response) {
// return response;
refresh();
});
};
this code is in my server.js:
var express = require("express");
var app = express();
//require the mongojs mondule
var mongojs = require('mongojs');
//which db and collection we will be using
var db = mongojs('contactlist', ['contactlist']);
//sendgrid with my API Key
var sendgrid = require("sendgrid")("APIKEY");
var email = new sendgrid.Email();
var bodyParser = require('body-parser');
//location of your styles, html, etc
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.post('/email', function (req, res) {
var curEmail = req.body;
console.log("Hey I am going to send this person a message:" + curEmail);
var payload = {
to : 'test#gmail.com',
from : 'test1#gmail.com',
subject : 'Test Email',
text : 'This is my first email through SendGrid'
}
sendgrid.send(payload, function(err, json) {
if (err) {
console.error(err);
}
console.log(json);
});
});
Currently the email is hard coded but I will make the change after I fix the post issue. If you could point me in the right direction that would be very helpful. Thank you.
Looks like you're expecting the request body to contain JSON, with this line:
app.use(bodyParser.json());
Your error in your console says Unexpected token, which leads me to believe that body-parser encountered something it couldn't parse as JSON... probably a string. Which means that you sent your email as a string in the request body.
The easy fix would be to change how you're sending the request client-side:
var data = { email: 'some#email.com' }; // as opposed to just 'some#email.com'
$http.post('/email', data).then(refresh);
use this code
$scope.send = function(contact) {
console.log("Controller: Sending message to:"+ contact.email);
$http.post('/email', contact).then(function (response) {
// return response;
refresh();
});
};
and at server side
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser());

Categories

Resources