trying to fetch datas from express.js using backbone.js - javascript

I am trying to build an application with backbone.js and express.js. I have an issue to return the values from express to backbone. I had the same problem with a simple Curl request (i could display req.params on the server side but impossible to get it on the client side, even using JSON.stringify() on it).
I did the same code with a simple echo json_ecode() in php and it works well...
Here is the code of a simple test on the server side:
var express = require("express");
var app = express();
app.get('/user/:id/:pass', function(req, res){
res.status(200);
res.send({"id": "1"});
});
On the client side, i don't get any of the success or error callaback...
var U1 = new User();
U1.fetch({
success: function(data) {
console.log('User fetched.');
},
error: function(model, error) {
console.log('user Error: '+error);
}
});
What is wrong with my answer on express.js ?
Thanks !

Ok i found the solution by adding res.header("Access-Control-Allow-Origin", "*"); in my express route.

As long as the User model sets it's url to the same /user/login/password then it should work, see: http://backbonejs.org/#Model-url Did you already create a url method on the User model?
I posted a couple articles on backbone.js and express ... http://www.pixelhandler.com/blog/2012/02/29/backbone-js-models-views-collections-to-present-api-data/ backbone example using API data from express app: http://pixelhandler.com/blog/2012/02/09/develop-a-restful-api-using-node-js-with-express-and-mongoose/

Related

In an express application ,how can the javascript file in public folder access the database API written in routes folder under index.js

Aim of the project is,accessing the mysql database at localhost/phpmyadmin on clicking a button from the client side and getting the data from the database for filling up a table on client side.
This project is done using an express application.
Code for database interface written under routes folder, index.js file:
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
'host':'localhost',
'user':'root',
'password':'',
'database':'displayu'
});
connection.connect();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.get('/getusers',function(req,res,next){
var x;
connection.query('SELECT * FROM sample', function(err,result,field){
if (err){
throw error;
}
else{
x = res.json(result);
console.log(x);
}
});
});
module.exports = router;
On localhost:3000 the client side code written in views folder under index.html and the javascript logic under public folder results in a button and an empty table.I want to make use of the code written under server side routes folder onclick of this button to access the database and fill this data into the table.
I don't know the exact steps to do this requirement. I have the client side code and the server side code but need help to link them both to get output.
As already suggested you can achieve that by doing an AJAX request from your client side js.
You could do this with native JavaScript by using the XMLHttpRequest utilities.
For example:
function populateTable() {
// Handle your data here..
}
var GetUsersData = new XMLHttpRequest();
GetUsersData.addEventListener("load", reqListener);
GetUsersData.open("GET", "/getusers");
GetUsersData.send();
You could also use jQuery, depending on your project. If you already use it, I'd recommend using the included jQuery.get() function, which is quite a bit simpler than using native JS.
If you are not using jQuery in your project at the moment, you should stick to doing it the JS native way, also depending on how many AJAX requests you want to make and also keeping in mind how many you have to manage/debug going forward.
Both of these ways are very interesting and I'd suggest reading up on at least one of them, as they are very useful and you will at some point have to use AJAX again.

How to fetch the data from in memory of Express?

Hello I am trying to mock the API using swagger and express, in which I require data stored from the in memory database.
Following is my code, by which I am not able to get the data and it gives me syntax error.
I am using petstore application for mock.
Following is the script I modified as per my need.
What is wrong with the script.?
app.get('/pets', function(req, res, next) {
var myDB = new MemoryDataStore();
myDB.get('/pets',function(err, res){
});
});

I use routes in my Node.JS app and when I try to open one of the routes from the browser I get an error

That's my app. When I try to open ip/delete I get an error
Cannot GET /delete
I'm following this tutorial, https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function(req, res) {
console.log("Got a GET request");
res.send('GBArena Labs');
})
app.post('/', function(req, res) {
console.log("Got a POST request");
})
app.delete('/delete', function(req, res) {
res.send('Delete');
console.log("Got a DELTE request");
})
app.listen(8081);
You can't navigate to a DELETE. You have to send a DELETE request. In example :
<a href="/delete">My delete link<a/> will be sent as a GET request and not a DELETE.
In order to hit your delete endpoint, you would have to use a ajax library like jquery $.ajax and using
$.ajax({
url: '/delete',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
from the client side.
There are many ways, but i would suggest you looking into : HTTP verbs
You may need to call the route without the /delete and use the HTTP verb DELETE from a REST client such as Fiddler or Postman.
First, you try to access by ip/delete endpoint. I assume you will get an error because you are not using the port of the application (you have to access by ip:port/delete)
You have to know about the usage of DELETE method. When you try to directly access the ip/delete endpoint, your browser will set it as GET method while in your application, there is not GET method for ip/delete

Send a response to Angular.js in Node.js

Im using Angular with Node and would to send a response to the client-side controller from a GET request.
The line of code Im using to send the response seems not to be working when I use native Node as opposed to Express.js
Here is my angular controller:
app.controller('testCtrl', function($scope, $http) {
$http.get('/test').then(function(response){
$scope = response.data;
});
});
This is routed to essentially the following server script:
http.createServer(function onRequest(req, res){
if(req.method==='GET'){
var scope = 'this is the test scope';
res.json(scope); // TypeError: res.json is not a function
}
}).listen(port);
res.json() throws an error unless I use an express server
var app = express();
app.all('/*', function(req, res) {
if(req.method==='GET'){
var scope = 'this is the test scope';
res.json(scope); // OK!
}
}).listen(port);
I was pretty sure the json() function came with node. How do I send a response back to angular when using a native Node server?
res.json is not in the API for HTTP response.
The standard way would be to use res.write() (docs) and then res.end() (docs). But in your case, since you're not sending a lot of data you can use a shortcut and just use res.end() with a data parameter :)

Value of request params is empty if i use = symbol with request value

I am working on node.js project which uses express framework .
My application will process bunch of POST requests . One of my post request is follows
URL
POST /processit
request params
info={"one":"a=5"}
node.js code
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/processit', function(req, res) {
console.log(req.body);
res.type('text/plain');
res.send('Testing !');
});
app.listen(process.env.PORT || 3000);
In node.js log i am getting respone
{}
But if i change request params from info={"one":"a=5"} to info={"one":"ab5"} i am getting
info={"one":"ab5"}
in node.js log .
I don't know whether i did anything wrong here
ScreenShot :
Thanks in advance .
I suspect your issue is with how your Eclipse test tool is encoding things.
Try doing your POST with curl from the command line, or this Chrome plugin: https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn?hl=en

Categories

Resources