Below are my Server's code
/* GET tone. */
router.post('/tone', function(req, res, next) {
console.log("what is the body" + req.body.data);
tone_analyzer.tone({ text: req.body.data }, function(err, tone) {
console.log(req.body.data);
if (err) {
console.log(err);
} else {
res.send(JSON.stringify(tone, null, 2));
}
console.log(req);
});
});
My Ajax's call in the html page.
function toneAnalysis(info){
$.ajax({
url: 'http://localhost:3000/tone',
type: 'POST',
data: info,
success: function(res) {
console.log("testing " + info);
},
error: function(xhr, status, errorThrown) {
console.log(status);
}
})
The server could not retrieve the req.body.data. When I tried to console log it, it always prints undefined. Could any one help me out with this? Thank you.
Update:
The printed req.body after I used body parser
Like the answer above mentioned you can use BodyParser and you can download it and install it using npm like so:
# npm install bodyparser --save
Then returning to your $.ajax call, you are sending some data represented in the data object, so using the BodyParser you can simply have an access to the sent object, because BodyParser add another object to the req nodejs object and it's called body, so if you want to access to all sent items using BodyParser you will probably going to do it like so :
const app = require('express')();
let bodyParser = require('body-parser');
// add a new middleware to your application with the help of BodyParser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//Configure the route
router.post('/tone', (req, res, next) => {
console.log("what is the body" + req.body.data);
tone_analyzer.tone({ text: req.body.data}, (err, tone) => {
console.log(req.body.data);
if (err){
console.log(err);
}
else{
res.send(JSON.stringify(tone, null, 2));
}
console.log(req);
});
});
Now using BodyParser, things can get really easy when you handle your XHR or HTTP calls.
your request body will be in req.body
if it is json you can use
let bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
router.post('/tone', function(req, res, next) {
console.log("what is the body" + req.body);
tone_analyzer.tone({ text: req.body},
function(err, tone) {
// your code here
}
Do you have this in your server configuration?
app.use(express.bodyParser());
This allows you to parse JSON requests.
Related
I am sending form data values using Postman as given here. Postman Request.
I am making use of NodeJS server in the backend to get the data from this POST request.
The code for my app.js file is given below.
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(bodyParser.json({
limit: '50mb',
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
const { multerUploadOneFile } = require(path.resolve(__dirname, 'helpers', 'multerConfig'));
app.post('/upload', function (req, res) {
// **Here I need to get the other parameters in the request body, i.e ```userId```, ```fileType```
console.log(req.body);
multerUploadOneFile(req, res, function (error) {
if (error) {
return res.status(401).send({
status: 'failure',
message: error.message
});
}
return res.status(200).send({
status: 'success',
message: 'successfully uploaded file.',
});
})
});
I am logging the request body in /upload api endpoint but I am not able to get anything. Please let me know how can I get the req.body in callback of /upload api endpoint.
body-parser doesn't support multi-part bodies.
multer (which you're correctly using) does, however it needs to execute and parse the request before you'll be able to access anything.
multerUploadOneFile needs to execute before you have acceess to .body or .file.
app.post('/upload', function (req, res) {
multerUploadOneFile(req, res, function (error) {
console.log(req.body, req.file);
I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them. i have looked at a number of similar questions on stackoverflow and have not been able to find an answer. Would appreciate if someone could please point out where i have gone wrong.
getListings.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config);
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
connection.query('SELECT listing_coords FROM listings', (err, rows) => {
if (err) throw err;
console.log('Data received from Db:\n');
var results = JSON.parse(JSON.stringify(rows));
module.exports = { results };
console.log(results);
});
});
Then in my script.js file i have
var { results } = require('./getListings');
console.log(results);
I am getting an error in the browser console saying "require is not defined"
I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way? Do i have to build an api and use ajax? Thanks in advance for any help.
have updated my getListings.js file - it now displays in the string of data i need in the browser as a raw data packet
var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
app.listen(5000, () => console.log('express server is running at 5000'));
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
I have been unsuccessful to get the output to run in script.js. I will post the working code when its working.
I am getting an error in the browser console saying "require is not defined"
It is because require is not an API for frontend. It should be the syntax of backend(eg. nodeJS).
Do i have to build an api and use ajax?
If you wanna to send data from frontend to backend. Using ajax is possible but the main point is you need to have a backend server(eg. using Express module for nodeJS) to connect with the database(eg. mysql, postgresSQL).
Update on 14 Feb, 2021
My practise for doing this is to use ajax to send a request to the backend server from frontend.
//frontend
$.ajax
({
url: "yourBackendServerUrl", //eg. localhost:8001/listing. Need modification based on your backend setting.
})
.done(function(data) {
console.log(data) //data should be the result from backend, then you can retrieve the data for frontend usage
});
For the CORS problem, you can install cors package. If you have a middleware in the global scope(a.k.a. app.use(cors()) ). Every time there are request, this middleware will run.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors()) // pay attention to this line of code.
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
The solution that I got to work is as follows:
getListings.js (this was nodeJS)
var mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
var app = express();
app.use(bodyparser.json());
**app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});**// I believe this is a middleware function
config = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'xx',
port: 'xxxx',
};
var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
if (err) {
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
app.listen(5000, () => console.log('express server is running at 5000'));// this can be any port that isnt currently in use
app.get('/listings', (req, res) => {
connection.query(
'SELECT listing_coords FROM listings',
(err, rows, fields) => {
if (!err) res.send(rows);
else console.log(err);
}
);
});
in my script.js file i was missing the following
$.get('http://localhost:5000/listings', function (data, status) {
console.log('Cords Data', data);
I believe that is the jQuery ajax
Then in the heading of my html I needed the following
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type = "module" defer src="script.js"></script>
thanks to everyone that helped me with this. especially #tsecheukfung01.
I dont fully understand all of the pieces so it will take me a while to fully understand this and be able to recreate this on my own. All part of the journey!
Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.
I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.
I have added body-parse as suggested but still no joy.
I will post my server code and request below.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.post('/api/save-json', (req, res) => {
console.log(req);
res.send(
`I received your POST request. This is what you sent me: ${req.body.json}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
My postman request is:
{
"body" :
{
"json": "some data"
}
}
Any ideas?
body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json
I'm trying to create a REST API using Node.js that would fetch the last N rows of a MongoDB collection. This is my current code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var mongodb = require("mongodb");
var MongoClient = require("mongodb").MongoClient;
var db;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/sample", function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here because most apps *should* fail to start if they have no DB. If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
}).limit(10,function(e,d){});
});
app.use('/',router);
app.listen(3000);
console.log("Listening to PORT 3000");
This is successfully printing out all of the contents of the database on the server console (Whenever the client makes a get request). However, how do I give this JSON information to the client making the GET call instead in an efficient way (and one that supports the situation where the client can add a parameter N that would only fetch the last N rows of the database). I looked into Mongoose and that seemed pretty solid but in my case I already have a pre-existing database and collection so wasn't sure if that was the best route for this task.
If you need any more info or clarification, feel free to let me know! Thanks for reading!
Instead of res.end, you would use res.send and send the response back to the front end.
router.get("/", function(req, res, next) {
db.collection("samplecollection").find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
var response = {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.parse(doc)
}
res.send(response);
}
});
});
});
To get the last N records of a collection, you could use a combination of sort and limit. First, sort on a specific field such as date in ascending/descending order and then limit the results to whatever N is. Something like this:
db.collection.find({ query }).sort({ key: 1 }).limit(N)
UPDATE:
Based on our ongoing comment conversation, here is an example of how I have successfully sent data back to the client. This does not include the limit or anything fancy.
var express = require('express');
var app = express();
var port = process.env.PORT || 3000;
var db = require('./config/db');
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/', function(req, res) {
db.find({}, function(err, data) {
if (err) {
console.log(err);
return res.send(500, 'Something Went wrong with Retrieving data');
} else {
// console.log(data[0]);
res.json(data);
}
});
});
app.listen(port);
console.log('Server listening on port: ', port);
Ended up fixing my issue. Changed my get statement to this:
router.get("/", function(req, res, next) {
db.collection("samplecollection", function(err, collection){
collection.find({}).limit(10).toArray(function(err, data){
res.json(data);
})
});
});
I'm quite new to AJAX, so sorry for potential missunderstandings, but I'm not completely through that thing.
I'm trying a simple thing. I have a server.js file, which is my backend basically. Then I have a index.html and a script.js. That's all, so a very basic setup. Now, on my script.js, I'm getting some data (a mail address). Now I want to send that data to my backend (into the server.js) to work with it there. How can I do this?
I found some posts already about AJAX with node.js, but I don't get it, especially not where to receive it in my backend. I'm using express for the server by the way.
What I have in my script.js is:
$.ajax({
type: "POST",
url: "server.js",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Right so far? How can I now receive the information in my server.js?
There's not much in so far, just:
var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
Thanks for any help :)
Note: This was written before the question was updated with the code so the field names and port numbers that I used here as examples may need to be updated with the correct values.
Client-side code - example with jQuery:
$.post('/email', { address: 'xxx#example.com' });
(this can take optional callbacks and it returns a promise that can be used to add a success/error handler)
Server-side code - example with Express:
const express = require('express');
const bodyParser = require('body-parser');
const dir = path.join(__dirname, 'public');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/email', (req, res) => {
// you have address available in req.body:
console.log(req.body.address);
// always send a response:
res.json({ ok: true });
});
app.use(express.static(dir));
app.listen(4443, () => console.log('Listening on http://localhost:4443/'));
This assumes that your static files (HTML, client-side JavaScript, CSS) are in the public directory relative to your server.js file.
See this for background on the JSON/form-encoding issue:
Which method is prefer when building API
See this for background on serving static files:
How to serve an image using nodejs
That's actually quite simple to implement in Express.JS with the basic router:
I'm gonna give you the minified code snippets to help you get sense of how it works across browser and server.
in Front-End, you basically just want to "post" an email address to the backend:
$.post('/email', { email: 'howareyou#xx.com' })
and in Back-End(Express.JS), you should implement the basic router:
var express = require('express');
var app = express();
// use: app.METHOD(PATH, HANDLER)
app.post('/email/', function(req, res) {
var email = req.body.email
})
Read more here: http://expressjs.com/en/guide/routing.html
First, you need a valid route to hit when the server is running. You can do this in server.js through express.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/mail', function(req, res) {
var body = req.body;
console.log('email', body.email);
res.json({ message: 'I got the email!' });
});
var server = app.listen(3000);
Notice I have brought in an express middleware that will parse the body for JSON and make it available on the req object under req.body. You will need to install this dependency with npm install --save body-parser.
Then you need to send a POST request to that URL from the front-end.
$.ajax({
type: "POST",
url: "/mail",
data: { mail: mail },
success: function(data) {
console.log('message', data.message);
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Now, if you submit an email, you should see a log in your terminal that shows the email and a log in your developer console in the browser that shows the message "I got the email!"
in server.js add this :
app.post('/searching', function(req, res){
//do something with req
});
and in script.js :
$.ajax({
type: "POST",
url: "/searching",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
First of all you nedd to create a route for the Mail
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var router=app.Router();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // Parse request body
app.use(express.static(path.join(__dirname, 'public')));
// Route to check Email
router.post('/CheckEmail',(req,res)=>{
var email=req.body.mail; // Get email here
})
app.listen(process.env.port || 3000,()=>{
console.log('server is running');
})
Ajax
$.ajax({
type: "POST",
url: "/CheckEmail", // post route name here
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
You need a few more things to actually be able to parse the body. Add this to your server.js file.
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
You need to specify a valid URL. Since you are listening on 3000. You also need to specify a route on your server as an endpoint.
$.ajax({
type: "POST",
url: "http:localhost:3000/",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Now you need to add a route on your server. You can do so by adding this to your server.js file after all of the app.use calls
app.post("/", function(req, res){
// your logic here
res.send("I am sending something back!");
})