I use $.ajax to request data from a node.js server. I'm debuging the client side in Firefox. I get the following error in the console: Syntax error Cannot GET /xyz where /xyz is the route for my server. However, the page works properly. I would like to avoid filling the console with this error because the AJAX request is done recursively.
Client code:
startUpdateGui = function(){
(function updateGui(){
$.ajax(
{
url: "/updategui",
type: "POST",
data: {
id: "master"
},
timeout: 10000,
}
).done( function( data ){
$( "#time_server" ).text( data );
updateGui();
});
})();
}
startUpdateGui() is called once at the end of <body>. Notice again that the function performs what I want it to do. done() is correctly executed.
Server code:
app.post( '/updategui', function( req, res ){
//log.mark( 'Routing \'/updategui\' with id = "' + req.body.id + '"' );
res.end( (new Date()).toString() );
});
where app is from Express.
So, looking at the client $.ajax(...) and the server app.post(...) can you see where the problem is?
Thanks for your help!
What version of jquery are you using? Is it prior to 1.9.0?
http://api.jquery.com/jquery.ajax/. Basically if you don't set it, it's defaulted to be get.
Anyway can you update that to method? Also you call the updateGui() inside updateGui().
I'm not sure if you want it
(function updateGui(){
$.ajax(
{
url: "/updategui",
method: "POST", // <---- updated
data: {
id: "master"
},
timeout: 10000,
}
).done( function( data ){
$( "#time_server" ).text( data );
updateGui(); // <--- recursion
});
})();
This is my Nodejs code.
var express = require('express');
var app = express()
.all('/updategui' , function(req, res, next){
// res.write('all\n');
next();
})
// app.get('/', function(req, res, next){
// res.end('get\n');
// })
.post('/updategui', function(req, res, next){
res.end('post\n');
})
app.listen(3000);
Related
I start learning Node.js and Express.js and I'm trying to create a simple API to list data from JSON file (using the GET method) and add a new user using the POST method.
the GET method works fine but the POST method does not work
when I request http://127.0.0.1:8080/listusers the API sends all users in a JSON file.
when I request http://127.0.0.1:8080/adduser the API has to add new User Info and send the new data back to the browser.
NOTE: I read all the questions on Stackoverflow about this problem but
non of them help me so I have to ask again.
the problem is when I request http://127.0.0.1:8080/adduser I get the following error
Cannot GET /adduser
here is the server.js:
var express = require('express');
var app = express();
var fs = require('fs');
var user = {
"user4" : {
"name" : "mounir",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
};
app.post('/adduser', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = user["user4"];
console.log( data );
res.end(JSON.stringify(data) );
});
});
app.get('/listusers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log(data);
res.end(data);
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("listening at http://%s:%s", "0.0.0.0", port)
});
The answer is in the error. Cannot GET /adduser. Keyword GET! If you are making a post request, be sure you include the appropriate headers and that you are making a POST request, with a body, and not a GET request. For instance if you are using fetch:
const myInit = {
method: 'POST',
headers: myHeaders,
body: {
...
}
};
fetch("http://127.0.0.1:8080/adduser", myInit)
.then(res => {
...
});
So I'm running a node.js server with express that has this data. Ultimately I am trying to submit close notes, from a form in my html page, to update the close notes in this data set, which is hard coded into the node server for now.
var data = [
{
inc_num: "INC0001",
close_notes: "blah"
},
{
inc_num: "INC0002",
close_notes: ""
},
]
these are the three back end http requests.
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.put('/update/:inc_num', (req, res) => {
delete data.close_notes;
var body = req.body
data.close_notes = body.close_notes;
res.status(200).send('ACK');
});
app.get('/update', (req, res) => {
res.send(data);
});
Here is the AJAX request from the front end
$.ajax({
url: '/update/' + inc_num,
type: 'PUT',
constentType: "application/json",
data: dataPut,
success: function(){
console.log('PUT SUCCESS');
}
})
The way it is right now nothing changes at all.
I know for a fact that the front end is sending the correct data through because if I change the function in the app.put to data.push(req.body) it adds the correct information I passed into the data array. I am either not understanding something about PUT request correctly or am just messing something up in the function of the back end PUT request.
Any help is greatly appreciated!
I am trying to send a data from client to server (node js) . I am using ajax .
client :
$("#test_button").on("click",function(){
//alert("shit");
$.ajax(
{url: "http://localhost:4000/ajax_check",
async: false,
type: "POST",
data: "{user:balayya,password:hero}",
success: function(result){
alert("hooli");
}});
});
server:
var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
http.listen(process.env.PORT || 4000, function() {
console.log('listening on *:4000');
});
app.use(express.static('publuc'));
app.get('/', function(req, res) {
console.log("new entry page serving");
res.sendFile(__dirname + '/main.html');
});
app.post('/ajax_check', function(req, res){
console.log("someone came in here");
console.log(req.query.data);
});
the console.log() is printing as "undefined" .
What is the correct way to receive a post request and it's data from the client in node js
Use this npm package - https://www.npmjs.com/package/body-parser
and so server site parse like this:
request.body.{some field name}
Try like this:
$.ajax({
url: "http://localhost:4000/ajax_check",
type: "POST",
data: {
user: "balayya",
password: "hero"
},
success: function(result) {
alert("hooli");
}
});
And on the server use req.body.param_name to read the corresponding parameter value:
app.post('/ajax_check', function(req, res){
console.log("someone came in here");
console.log(req.body.user);
console.log(req.body.password);
});
Also notice that I have removed async: false from your AJAX request because every time someone sets this property to false a poor kitten dies.
the client code :
self.getjson = function () {
var timeinfo = new Object();
timeinfo.time = self.time;
timeinfo.address = self.address;
timeinfo.info = self.info;
return JSON.stringify(timeinfo);
};
alert(self.getjson());
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url:'/user/add/timetemp',
data: self.getjson(),
beforeSend: function (xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
}
})
the server code app.js:
router.route('/user/add/timetemp')
.post(function(req,res){
console.log(req.body); // your JSON
res.send(req.body); // echo the result back
});
the answer from client:
enter image description here
there has data in the client.
the answer from server:
but the server is null
From the documentation:
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.
(My emphasis.) It continues with:
The following example shows how to use body-parsing middleware to populate req.body.
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body);
res.json(req.body);
});
Side notes:
1. All of these variables on self are global variables. Global variables are a Bad Thing™. :-) Generally best to put your code in a scoping function and use locals within that scoping function.
2. new Object is almost never needed. Your getjson function can be much simpler:
self.getjson = function () {
return JSON.stringify({
time: self.time,
address: self.address,
info: self.info
});
};
or (slightly more convenient when debugging):
self.getjson = function () {
var timeinfo = {
time: self.time,
address: self.address,
info: self.info
};
return JSON.stringify(timeinfo);
};
3. There's no need for your beforeSend callback on ajax; just use the built-in contentType option:
$.ajax({
type: "POST",
//beforeSend:function(){$(".info").fadeIn('slow').html("正在提交,请稍后");},
url: '/user/add/timetemp',
data: self.getjson(),
contentType: 'application/json',
success: function(data) {
}
});
I am using express-http-proxy to proxy a backend server.
I would like all requests to /proxy viz /proxy/apples/brand or /proxy/oranges/brand/nnnn etc to be proxied to the backend service.
So, I have a wild card proxy set up here.
'use strict';
var express = require('express');
var proxy = require('express-http-proxy');
var app = express();
// ""
app.use('/proxy*', proxy('https://backend-server.com/' ,{
forwardPath: function(req, res) {
console.log(req.url)
return require('url').parse(req.url).path;
}
}));
var port = 3000;
app.listen(port, function() {
console.log('listening on port ' + port + '.')
});
I expect this
https://localhost:3000/proxy/oranges/brand/nnnn to be proxied to https://backend-server.com/oranges/brand/nnnn
But I just get
Cannot GET /proxy/aa
.I am not sure what's wrong here. The wild card routing looks pretty ok. Any thoughts here?
You could try request module. This solution perfectly works for me
var request = require( 'request' );
app.all( '/proxy/*', function( req, res ){
req.pipe( request({
url: config.backendUrl + req.params[0],
qs: req.query,
method: req.method
}, function( error, response, body ){
if ( error )
console.error( 'Wow, there is error!', error );
})).pipe( res );
});
Or if you still want to use express-http-proxy you need to write
app.use( '/proxy/*', proxy('https://backend-server.com/', {
forwardPath: function( req, res ){
return req.params[0];
}
}));