I was trying to post some data from my php page to my node.js server.and I want to get the response from it.
This is the ajax code which I was sending from my php page which is currently executing on the apache server
function encryptCode()
{
var value = document.getElementById("code").value;
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(value),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
and I just want to receive it in my node.js page by this code
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(data);
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
});
This is a controller of my express.js,which I have redirected from my app.js page with this code
app.all('/insertUser', attachDB, function(req, res, next) {
insertUser.run( req, res, next);
});
will somebody please help me out in the console.log I am getting {} .....
First test is it problem with the frontend.
function encryptCode()
{
var value = document.getElementById("code").value;
console.log(value);
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: {"user":value},
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(data)
{
alert(data);
}
});
}
You should set json body parser in your express app
var app = express();
bodyParser = require('body-parser');
app.use(bodyParser.json());
where did you declare data variable. In node.js the data sent through ajax request is available at req.body
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
console.log(req.body);
// console.log(req.body.user);
},
});
Related
I'm trying to send data to server.
My Ajax call:
$.ajax({
url: config.api.url,
type: config.api.method,
contentType: config.api.contentType, // application/x-www-form-urlencoded; charset=UTF-8
dataType: config.api.dataType, // JSON
data: config.api.dataType === 'GET' ? {} : JSON.parse(tmp),
headers: config.api.headers,
success: (response) => { onSuccess(response); },
error: (error) => { onError(error); }
});
My data:
{
sort: { name: 1 }
}
// I set name property by sort['name'] = 1; at js
But the server received:
{ 'sort[name]': 1 }
My nodejs server code:
exampleData = (req, res) => {
var sort = req.body.sort;
console.log(sort); // undefined
console.log(req.body); // { ..., 'sort[name]': 1 }
}
Chrome Form Data:
So, I can't read object correctly like an object sent from ajax request, something went wrong?
How can I fix it?
I hope you are using express.js. If yes then you need body parser middleware.
var app = require('express')(),
bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', function (req, res) {
console.log(req.body);
});
This question already has answers here:
How to access POST form fields in Express
(24 answers)
Closed 5 years ago.
server.js:
var express = require('express');
var app = express();
loggedIn = {};
app.use('/',express.static('www')); // static files
app.listen(8080, function () {
console.log('Port 8080!');
});
app.get('/user', function(req, res) {
if (typeof req.param('user') != 'undefined') {
user = req.param('user');
res.status(200).send('Works');
}
});
app.post('/user', function(req, res) {
user = req.param('user');
if (typeof users[user] != 'undefined') {
return res.status(405).send('Access Forbidden');
} else {
loggedIn[user] = "";
res.status(201).send('New User');
}
}
});
client.js requests:
$.ajax({
method: "GET",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
$.ajax({
method: "POST",
url: "/user",
data: {"user" : user},
dataType: "application/json",
success: function(data) {
// success
},
error: function() {
// error case
}
});
Even though the GET request works exactly as expected and passes the parameter here, for some reason, the post request doesn't. In firebug, I notice the POST request receives no parameters whatsoever (POST user) while GET request does (GET user?user=XYZ). I am really at a loss right now.
You have to tell your express app to parse the request body
app.use(express.bodyParser());
for express 4+
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/json
app.use(bodyParser.json())
For reference goto https://expressjs.com/en/4x/api.html#req and look at the section titled req.body
I am posting data via jQuery $.ajax() call like so:
var data = {};
data.name = $("#name").val();
data.email = $("#email").val();
data.message = $("#message").val();
$.ajax({
type: "POST",
url: "http://myHost/contact/sendEmail",
data: data,
contentType: "application/json",
dataType: "json",
success: function (data) {
console.log("success");
}
});
Which is then getting routed by contactRoutes.js:
contactRouter.route("/sendEmail").post(contactController.sendEmail);
To a controller which is supposed to pull the body of the request to then make an API call and send the email message.
sendEmail:
var sendEmail = function(req, res) {
var payload = {
to: req.body.email,
from: "noReply#test.com",
subject: req.body.name,
text: req.body.message
};
...Omitted for brevity
};
The error I continue to receive is SyntaxError: Unexpected token n in the body-parser module. I have app.js setup like this:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
I'm lost as to where to look. I've examined my JSON object and it appears correct, but obviously I'm missing something. Anyone have any suggestions? Also, how can I be sure that contactRoutes.js is picking up the content passed in data?
hi all I have a code like this
var BaseController = require("./Base"),
View = require("../views/Base"),
model = new (require("../models/ContentModel"));
module.exports = BaseController.extend({
name: "insertUser",
content: null,
run: function(req, res, next) {
model.setDB(req.db);
var self = this;
req.body = _.omit(req.body, '__proto__');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(req.body));
/*this.getContent(function() {
// var v = new View(res, 'place');
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(self.content));
});*/
// console.log("go to hell");
},
but it is sending me response in this FORMAT
{"{\"code\":\"Øù4\n\u0013¦é\",\"Age\":25}":"","proto":{}}
I just want remove "proto":{} or specifically to sal I want to get the output like this
"{\"code\":\"Øù4\\n\\u0013¦é\",\"Age\":25}"
will you guys please check where I am making the bug or the error
well,I am send the ajax request to the controller by this process
function encryptCode()
{
var value = document.getElementById("code").value;
var key = "secretKeyToProvide"; /*--Provide Your secret key here--*/
var codeValue = rc4(key, value);
var arr = {code:codeValue, Age:25};
var request =
$.ajax({
url: "http://localhost:3000/insertUser",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: "application/x-www-form-urlencoded", //This is what made the difference.
});
request.success(function(result) {
var value = JSON.stringify(result);
alert(value);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
how to get rid of this "proto"
Hi so I have a jquery post data that i'm sending:
$.ajax({
type: "POST",
url: app.config.backend_2 + '/notifications/usernames',
data: data,
contentType: 'application/javascript',
dataType: 'json',
success: function (result) {
console.log(result);
}
});
and this is my express receiver:
exports.save_usernames_for_notifications = function (req, res, next) {
var start = function () {
console.log(req);
};
start();
};
What do I do to get the data from the ajax to log it in the save_username_for_notifications function?
You need a body parser middleware in your expressjs application to parse your JSON req object
https://www.npmjs.com/package/body-parser
To configure it, you need this code
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // this is used for parsing the JSON object from POST
Then to get your data in your express application just do this
console.log(req.body.data)