Send AJAX data to node express - javascript

I am trying to send data with AJAX to node express, but as I handled it without express module (with if (req.method="POST"){function on data...})
as I can catch it with express.
NODE code to catch data:() for now nothing happens even in console.log)
app.get('/getdata',function(req, res){
res.send('Something');
});
app.post('/getdata', function (req, res){
console.log(req.body.objectData);
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) });
});
app.listen(process.env.PORT || 5073);
A HTML page with AJAX call:
$(document).ready(function () {
$('#Send').on('click', function () {
var toSend = $('#Sth').val();
alert(toSend);
$.ajax({
type: "POST",
dataType: "json",
data: { objectData: toSend },
contentType: "application/json",
cache: false,
url: 'http://127.0.0.1:5073/'
});
});
});
<body>
<input id="Sth" type="text" name="Content" />
<div id="select_div">Test</div>
<div id="test"> Content to be copied</div>
<input id="Send" type="submit" />
</body>
Well, I do not know what to do, please help.

Care to give this a shot?
app.post('/endpoint', function(req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
https://gist.github.com/diorahman/1520485

Related

Cross origin request block Node.js

i have a simple code that makes ajax interactions, it used to work perfectly about 1 week ago, but when i checked it today it says in the console : Blocking a Cross-Origin Request: The "Same Origin" policy does not allow the remote resource located at http://localhost:8080/api/user. Reason: CORS request failed.
I use firefox so i installed the plugin Cors everywhere, but no results yet.
My code :
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Hello World!</h1>
<div>
<h1>Sending User</h1>
<form id="userForm">
<label for="name">Name</label>
<input id="name" name="name"/>
<br/>
<label for="age">Age</label>
<input id="age" name="age"/>
<br/>
<input type="submit" value="Send"/>
</form>
</div>
<br/>
<br/>
<div>
<h2>Click the button below for getting User from server and showing it</h2>
<button id="getUserButton">Get User</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(document).ready(function () {
$('#userForm').submit(function (e) {
var user = {
name: $('input[name=name]').val(),
age: $('input[name=age]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/user',
data: user
})
.done(function (data) {
// clear form
$('input[name=name]').val('');
$('input[name=age]').val('')
alert(data);
});
e.preventDefault();
});
$('#getUserButton').click(function (e) {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/api/user'
})
.done(function (data) {
alert(JSON.stringify(data));
});
});
});
</script>
</body>
</html>
test.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userStoredInMemory = {};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/api/user', function (req, res) {
res.json(userStoredInMemory);
});
app.post('/api/user', function (req, res) {
userStoredInMemory = req.body;
res.send('User was already stored from express.');
});
app.listen(8080, function () {
console.log('server up and running at 8080 port');
});

Ajax fails when sending a data object to the NodeJs server

when pressing a button this code gets executed
function submitData() {
$.ajax({
type: 'GET',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: JSON.stringify({ // some test data
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
})
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this
app.get('/questionnaire/submit', function (req, res) {
var data = req.query; // Get the data object from the Ajax call
console.log(data);
res.send(null); // Send nothing back
});
Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.
Even when writing res.send("Success"); the client will log "Error". What am I missing?
Update:
I installed the body parser middleware and use this code now
my app.js
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const handlebars = exphbs.create({
defaultLayout: 'index',
extname: 'hbs'
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'Public')));
app.listen(8888, function () {
console.log('Server running on port 8888');
});
my route
module.exports = function (app) {
app.get('/questionnaire', function (req, res) {
res.render('questionnaire');
});
app.post('/questionnaire/submit', function (req, res) {
var data = req.body;
console.log(data);
res.send(null);
});
};
and my client function
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
dataType: "json",
data: JSON.stringify({
satisfactory: $("#edtSatisfactory").val(),
improvement: $("#edtImprovement").val(),
rating: currentRating / ratingElements.length
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
And when executing the Ajax call the client still runs into .fail()
Client request is :
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: {
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
}
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this Using bodyParser middleware in your node backend
:
app.post('/questionnaire/submit', function (req, res) {
var data = req.body; // Get the data object from the Ajax call
console.log(data);
res.end(); // Send nothing back
});
You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.
url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext
If you're using POST don't forget:
'Content-Type': 'application/json',
Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:
npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
This will parse your JSON and add it to req.body.
Try this..
Client Side
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
'Content-Type': 'application/json',
data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
}).done(function () {
console.log('hi')
}).fail(function () {
console.log("Error");
});
}
On server Side:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/questionnaire/submit', function (req, res) {
var data = req.body
console.log(data);
res.send(null); // Send nothing back
});
You have to install body-parser library using following command.
npm install --save body-parser
It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question.
If you are not understanding anything plz comment below.
You just have to replace
dataType: "json",
with this:
'Content-Type': 'application/json'
in $.ajax request
Hope this will work.. I have tried & tested.

How do I get an image from a folder using Ajax and Nodejs?

So, I want to upload a picture and show it right below the page so it looks like I am "posting" the picture.
So here's what I did in NODEJS:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/img');
},
filename: function (req, file, cb){
cb(null, file.originalname);
}
});
var upload = multer({storage: storage});
app.post('/', upload.single('file'), function(req, res){
res.send(req.file);
});
So right now every time I upload a picture it goes right into the folder called 'img'.
Now I want to retrieve this img using ajax and that's what I did in JAVASCRIPT:
$("input[type=submit]").click(function(){
$.ajax({
type: 'POST',
url: '/',
success: function(data){
console.log(data);
}
});
});
However, I don't get anything from the success function in ajax, rather, I just go to another page where I can see this json:
{
fieldname: "file",
originalname: "extensao.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/img",
filename: "extensao.jpg",
path: "public/img/extensao.jpg",
size: 411576
}
How can I make this work and receive this JSON in my success function? I thought by doing res.send(req.file) I was already sending the data to my ajax request.
after you've saved the images, you can get them by using this piece of code. This will send the file to the user. Let's say you have a file named jeff.jpg inside ./public/img all you have to is to go to yourlink.com/files/jeff.jpg to retrieve it.
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + 'public/img/' + req.params.filename);
})
This means that you can also render the images in your html by only using img tag. For example,
<img src="./public/img/jeff.jpg"/>
This is the whole code to my main.js file,
var express = require('express')
var multer = require('multer')
var app = express();
var whereFilesAreStored = '/public/img';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + whereFilesAreStored) //you tell where to upload the files,
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({storage: storage,
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
});
app.set('view engine', 'ejs');
app.get('/', function(req, res, next){
res.render('mult'); //our html document
})
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + whereFilesAreStored + '/' + req.params.filename);
})
//file upload
app.post('/post', upload.single('file'), function (req, res, next) {
console.log(req.file);
return false;
})
app.get('/ajax', function(req, res){
res.render('ajax');
})
To use the images in the client side, I have made a file named ajax as you can see above. this is my html.
Using ajax at this point is useless, it is only used to check if there's any updates on a page. But still I have made a small code for ajax for you to see. Don't use ajax for this task. you can use <img src="thelink"/> to get the file to your page. Please check my img tag down below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Anasayfa</title>
<link type="text/css" rel="stylesheet" href="/cssDosyalari/ana.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
var theUrl = 'http://localhost:2222/files/';
var fileName = "jeff.jpg";
var wholePath = theUrl + fileName;
$.ajax({
type: 'GET',
url: wholePath + fileName,
success: function(data){
console.log(data);
}
});
</script>
<img src="http://localhost:2222/files/jeff.jpg" alt="">
</body>
</html>
UPDATE
I have had problems with using ajax to it. Some reason, the link redirects me, so I have came up with this solution. I send the ajax, the server uploads the file, then makes the client reload the page with the image coming out. I am using ejs + ajax in here. Please check the code down below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
$('#my-form').submit( function(e) {
e.preventDefault();
//function myFunc(){
$.ajax({
url: '/post',
data: $('#myFile'),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
})
e.preventDefault();
console.log('ajax sent');
return false;
// }
}
//onclick="myFunc()"
</script>
<form id="my-form" action="/post" method="post" enctype="multipart/form-data">
<input id="myFile" type="file" name="afile" value="">
<input type="submit" name="" value="submit">
</form>
<img id="theImgSrc" alt="">
<script type="text/javascript">
$( document ).ready(function() {
$('#theImgSrc').attr('src', 'http://localhost:2222/files/<%=fileName%>').load();
});
</script>
</body>
</html>
This is my main.js file,
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + whereFilesAreStored + '/' + req.params.filename);
})
app.get('/', function(req, res, next){
res.render('mult', {fileName: ''}); //our html document
})
app.post('/post', upload.single('afile'), function (req, res, next) {
res.render('mult', {fileName: req.file.originalname});
console.log(req.file);
})

How to POST file via jQuery to nodejs connect-busboy

I can successfully send a file to connect-busboy by using an HTML form's action attribute like so:
<form ref='uploadForm' method="post" action="http://localhost:3000/fileupload" enctype="multipart/form-data" id='uploadForm'>
Select file to upload:
<input type="file" name="sampleFile">
<input type="submit" value="Upload!">
</form>
However, I would prefer to not have my page redirect.
I tried to convert this to jQuery by removing the action attribute in the form tag and adding an onclick function with the following:
$.ajax({
url:'http://localhost:3000/fileupload',
type:'post',
contentType: 'multipart/form-data',
data:$('#uploadForm').serialize(),
success:function(){
alert('Success');
},
error: function() {
alert('Error');
},
});
Unfortunately, this doesn't work with the error:
TypeError: Cannot read property 'end' of undefined
The Nodejs code is as follows:
const express = require('express');
const busboy = require('connect-busboy');
const app = express();
app.use(busboy());
const fs = require('fs');
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filen ame);
console.log(fstream);
file.pipe(fstream);
fstream.on('close', function () {
res.send('Success');
});
});
});
var port = process.env.PORT || 3000;
app.listen(port);
Full error: http://i.imgur.com/vUqmjWS.png
By explicitly serializing the form you are implicitly avoiding/removing the multipart/form-data format. Instead, pass a FormData instance as the data. You can instantiate a new FormData from an existing form like:
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'http://localhost:3000/fileupload',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: data,
success: function() {
alert('Success');
},
error: function() {
alert('Error');
}
});

How to send data from server to client in nodejs?

I'm running a server in nodejs with express to serve an html form within the file index.html to a client like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
res.json(req.body);
});
app.listen(8080);
req.body gives me the form input. Now I need to send back req.body to the client, and to do this I'm using ajax on the client side (inside index.html) like this:
var data;
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: data,
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})
However when I click the button submit I get Object {} in the browser console and not the form input.
What am I missing here?
There are two issues in your code:
First, as the comments mention, bodyParser() is deprecated, you should be using the specific bodyParser middlewares (json, text, urlencoded, raw). So in your case:
app.use(bodyParser.json())
Second, your client side call to jQuery.ajax should stringify your data. Like this:
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: JSON.stringify(data),
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})

Categories