-
-
Save diorahman/1520485 to your computer and use it in GitHub Desktop.
<html> | |
<head> | |
<title>jsonp test</title> | |
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script> | |
<script type="text/javascript"> | |
$(function(){ | |
$('#select_link').click(function(e){ | |
e.preventDefault(); | |
console.log('select_link clicked'); | |
/*$.ajax({ | |
dataType: 'jsonp', | |
data: "data=yeah", | |
jsonp: 'callback', | |
url: 'http://localhost:3000/endpoint?callback=?', | |
success: function(data) { | |
console.log('success'); | |
console.log(JSON.stringify(data)); | |
} | |
});*/ | |
var data = {}; | |
data.title = "title"; | |
data.message = "message"; | |
$.ajax({ | |
type: 'POST', | |
data: JSON.stringify(data), | |
contentType: 'application/json', | |
url: 'http://localhost:3000/endpoint', | |
success: function(data) { | |
console.log('success'); | |
console.log(JSON.stringify(data)); | |
} | |
}); | |
/*$.ajax('http://localhost:3000/endpoint', { | |
type: 'POST', | |
data: JSON.stringify(data), | |
contentType: 'application/json', | |
success: function() { console.log('success');}, | |
error : function() { console.log('error');} | |
});*/ | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<div id="select_div"><a href="#" id="select_link">Test</a></div> | |
</body> | |
</html> |
var express = require('express'); | |
var app = express.createServer(); | |
app.use(express.bodyParser()); | |
/*app.get('/endpoint', function(req, res){ | |
var obj = {}; | |
obj.title = 'title'; | |
obj.data = 'data'; | |
console.log('params: ' + JSON.stringify(req.params)); | |
console.log('body: ' + JSON.stringify(req.body)); | |
console.log('query: ' + JSON.stringify(req.query)); | |
res.header('Content-type','application/json'); | |
res.header('Charset','utf8'); | |
res.send(req.query.callback + '('+ JSON.stringify(obj) + ');'); | |
});*/ | |
app.post('/endpoint', function(req, res){ | |
var obj = {}; | |
console.log('body: ' + JSON.stringify(req.body)); | |
res.send(req.body); | |
}); | |
app.listen(3000); |
Thanks for sharing !!!
I am getting following error:
`throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please s
ee https://github.com/senchalabs/connect#middleware.');
^
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.
com/senchalabs/connect#middleware.
at Function.get (C:\Users\Sachin\Desktop\IM-POC\ajax-example\node_modules\express\lib\express.js:99:13)
at Object. (C:\Users\Sachin\Desktop\IM-POC\ajax-example\main2.js:4:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)`
Hello,
I am getting the following error:
var app = express.createServer();
^
TypeError: express.createServer is not a function
at Object. (C:\Node Projects\file_upload_sid\app.js:2:19)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
Kindly, let me how to resolve this issue
Thanks,
Siddharth
I am beginner in Node.JS . Finally, i got my answer after many hours of surfing the web by reading your article. hope to see more posts on this technology.
Its an awesome post and is quite meaningful.
Man, this is still relevant in 2017. Thanks for posting this, i was about to pull the last remaining hair off my head but you sir saved me from total baldness!
thanks its worked
Saved my ass. Thank you so much! Update for people living in 2018 and beyond: app.use(express.bodyParser());
no longer works because it is not included in Express like it used to be. So instead, go to your command line and type npm install body-parser
and let that download. Then replace app.use(express.bodyParser());
with:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Then everything else should work like normal. Rock on and make cool things
thank so much very muchhhh
Thanks man !
But I would like to know in case of deployment where we are in HTTPS, will this code run ? because in the url of the ajax request it is http
rtwaltz thanks bro
DaoFof it should be fine its working for me!
Good job! Exactly what i need.
Thanks breh.
@rtwalz thanks buddy!
Thank you so much for sharing this!
Thanks!!!
I have a problem:
Here's my client.js code:
$(document).ready(function () { var data = { title: "title", message: "message" }; $.ajax({ type: "POST", url: "http://localhost:8080/ls", contentType: "application/json", dataType: "json", data: JSON.stringify(data), crossDomain: true, success: function (data) { console.log(data); console.log(999); }, error: function (err) { console.log(err); } }); });
and my server.js code:
`var express = require('express');
var exec = require('child_process').exec;
var path = require('path');
var app = express();
app.set('views', 'public');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.render('home');
});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.set('views', 'views');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'public'))
app.get('/', function (req, res) {
res.render('corason');
});
app.post('/ls', function (req, res) {
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(8080, function () {
console.log('SERVER STARTED ON PORT 8080');
});`
when the ajax does the request I get:
XML Parsing Error: no root element found Location: http://localhost:8080/ls Line Number 1, Column 1: ls:1:1
Please help!
Hello I have this Error --> Failed to load http://localhost:3333/endpoint: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
What should I do? Thanks.
Thank you so much been on this problem over for 5 hours
I want the form with id logout to work;
Nothing coming on console Someone help
JS
<script type="text/javascript"> console.log('ajax'); $(function(){ $('li form').on('submit',function(){ console.log('ajax3'); $.ajax({ type:'POST', url : '/logout', success : function(data) { location.reload(); } }); }); }); </script>
Inside body
<nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav" id="j"> <li class=""> <a href="homepage"> <span class="glyphicon glyphicon-home"></span> HOME</a> </li> <li class="scroll"> <a href="gallery"> <span class="glyphicon glyphicon-piggy-bank"></span> GALLERY</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li style="margin-right: 10px"> <button class="btn btn-default navbar-btn"> <span class="glyphicon glyphicon-user"></span> Hello <%=sess_data.user %> </button> </li> <li> <form style="padding: 0px;margin: 0px" id="logout"> <button class="btn btn-primary navbar-btn" type="submit"> <span class="glyphicon glyphicon-user"></span> Log Out</button> </form> </li> </ul> </div> </div> </nav>
Thanks !
tysm!
Thanks, I have used the following for this purpose and totally nailed the issue:
`var express = require('express');
var app = express();
var cors = require('cors');
app.use(cors());
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use((err, req, res, next) => {
return res.send({ "statusCode": util.statusCode.ONE, "statusMessage": util.statusMessage.SOMETHING_WENT_WRONG });
});
app.post('/post', function(req, res){
var response = {
'dest': '/public/'
}
res.send(response);
});
app.listen(3000);`
Thank you so much for sharing this ..!
I was stuck for a few days because of this problem.
//100% work
``//view data
$(document).on('click','.view',function(e){
e.preventDefault();
let id=$(this).attr('data')
$('#myModal').modal('show');
$.ajax({
type: "PUT",
url: "/updatemeeting/"+id,
dataType: "json",
data: JSON.stringify({id:id}),
contentType: 'application/json',
cache: false,
timeout: 5000,
complete: function() {
console.log('process complete');
},
dataType: "json",
success: function (response,status, xhr) {
var html = "";
html=html+"ID"+response._id+"";
html=html+"MetingName"+response.meetingName+"";
html=html+"Description"+response.description+"";
html=html+"StartTime"+response.startTime+" PM
";
html=html+"EndTime"+response.endTime+" PM
";
html=html+"Date"+moment(response.createDate).format('ddd Do MMM')+"";
$("#tableview").html(html);
},
error: function(xhr,status,error) {
console.log('process error',error);
},
});
})
//controller file
async AjaxView(req,res){
var id = req.params.id;
console.log("id=>",id);
if(!id){
req.flash('error','Something error')
}
const data=await Meeting.findOne({_id:id,moment:moment},(err,response)=>{
res.json(response);
})
console.log(data)
}
//route
app.put('/updatemeeting/:id', auth, MeetingController().AjaxView)
Thanks so much
Thanks!!!