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);
});
Related
I am using expressJS on the back end to make a very simple API since I am a beginner. I am sending a request to the back end from the front end and I expect the front end to receive a response. This works fine until I change the nodejs for it to make a second request before sending the original response back to the client. The process looks something like:
Front end sends a POST request
back end receives request, then:
makes its own POST request to a source
waits for this data to come back, then:
sends back a response to the original request from the front end including the data gotten from the second request.
This process works fine when I remove the few lines of code which send the second request, but when the NodeJs back end makes this second request, I get a 404 error returned to the front end - and this error does not come from the second request.
Here is the code:
front end:
function post() {
return new Promise(() => {
$.ajax("URL of my nodejs backend", {
method: "POST",
cache: false,
data: {
action: "test-https"
},
}).then(response => {
console.log(response);
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
nodejs backend (only the bits needed for this question)
const express = require("express");
//const $ = require("./djax.js");
const https = require('https');
const app = express();
app.post("/", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
const body = [];
req.on("data", (chunk) => {
body.push(chunk);
});
req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
//res.status(200).send("bod" + parsedBody);
// Now parsedBody will be like a query string: key1=val1&key2=val2
const queryObject = new URLSearchParams(parsedBody);
parseRequest(queryObject, res);
//console.log(parsedBody);
});
//console.log(body);
next();
});
function parseRequest(queryParameters, response) {
// Here, queryParameters is a QueryParams object holding the body of the request
// sendResponseFunc is the function which sends back the response for this
// current request.
// Now, we have access to the body of the request and we can use this
// to call the neccessary functions and logic, after which
// send a response back to the front-end via the second
// parameter
const action = queryParameters.get("action");
switch(action.toLowerCase()) {
// ... other cases ...
case "test-https":
sendHttpsRequest(response);
break;
default:
response.status(200).send("Error: unknown action:'" + action.toLowerCase() + "'");
break;
}
}
function sendHttpsRequest(response) {
const postData = JSON.stringify({
works: true
});
const postOpts = {
host: "httpbin.org", // This is a test-server. Not mine.
path: "/post",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData)
}
};
const newReq = https.request(postOpts, result => {
result.setEncoding("utf8");
res.on("data", chunk => {
console.log("Response" + chunk);
response.status(200).send("Request made from NodeJS end came back " + chunk);
});
});
newReq.write(postData);
newReq.end();
}
When I change the sendHttpsRequest function so that it does NOT make a request, like so:
function sendHttpsRequest(response) {
response.status(200).send("Hi");
}
... then the front-end receives the response and there is no error. There is a 500 internal server error only when the second request is made - when the function sendHttpsRequest is like in the penultimate snippet. I have tried to fix this for two days but I have no idea why this error is happening.
How can I make this second request from the NodeJS server and send back the contents of that without causing the 500 error?
You need to have error handling. You cannot expect that external requests will succeed all the time, for that reason you have to have res.on("error", ...) to respond the client appropriately.
However, I don't see a special case why you are using a data listener to collect payload chunks, it can be simplified very much.
Here is a very simple working example for you
// Backend
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(express.json()); // Accepts JSON as a payload
app.use(cors());
app.post('/', (req, res) => {
axios
.get('EXTERNAL URL')
.then((response) => {
console.log('Received payload', req.body);
// Handle response
res.json({data: response.data}).status(201);
})
.catch((error) => {
// Handle error
res.json({
message: error.message,
code: 422})
.status(422);
});
});
app.listen(port, '0.0.0.0', () => console.log(`Started at //127.0.0.1:${port}`));
Required dependencies are
ExpressJS cors package
Axios HTTP client
Axios can be used in browsers as well
Here is your jQuery Ajax request which sends JSON payload instead of FormData
// FE jQuery
function post() {
return new Promise((resolve, reject) => {
$.ajax('http://127.0.0.1:3000', {
contentType: 'application/json; charset=utf-8',
dataType: 'json',
method: 'POST',
data: JSON.stringify({
action: 'test-https',
}),
success: (data) => resolve(data),
error: (err) => reject(err),
});
});
}
post().then(console.log).catch(console.error);
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'm working on this simple Form application using Nodejs as my Server side. I'm able to receive the JSON object data sent by the Ajax call to Node. But my issue is that when I add a new property to my JSON object that will allow me to upload a file (data location: $('input[type=file]')[0].files) the server doesn't get it and it throws me an error.
So how can I attach a new property that holds a file value to my json object so my server can receive it? or do I need to change my Ajax call differently?
Here's my code:
script.js
$("form").submit( function() {
hideError();
submit = submitAnswers();
if(submit == true){
var jsonData = createJson();
$.ajax({
url: '/form',
type: 'POST',
dataType: 'json',
data: jsonData,
// enctype: 'multipart/form-data',
// //contentType: 'application/json',
error: function(err){
console.log(err);
showError(err.responseText);
}
});
}
});
function createJson(){
var answers = $("form[name = quizForm] input[type=radio]:checked")
var results = {
authority: answers[0].value == 'a',
sharing: answers[1].value == 'a',
accuracy: answers[2].value == 'a',
quality: answers[3].value == 'a',
complete: answers[4].value == 'a',
format: answers[5].value == 'a',
type: answers[6].value == 'a',
ownership: answers[7].value == 'a'
datalocation: $('input[type=file]')[0].files
}
return results;
}
Server Code
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.sendfile('./public/html/form.html');
});
router.post('/', function(req, res, next) {
/*This verifies that json data was sent to Server after being executed by the Ajax call*/
console.log('Request received: ');
console.log(req.body) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
console.log('\nRequest recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url
res.end('callback(\'{\"msg\": \"OK\"}\')');
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);
},
});
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)