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){
});
});
Related
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.
I’m building an API for a SPA built with Angular 2, for this app I have a stand alone API and than an Angular 2 app. So they are on built on two separate node.js servers. I’m using node.js and express along with 'express-connection' and 'mysql' modules to build a secure API to handle login and registration with JWT’s (json web tokens), along with other tasks of course. So I’ve successfully built this API so I can access data with my Angular 2 app via a URL. I can use the URL ’localhost:3000/data’ to access a json data object from my Angular 2 app running on 'localhost:3001/'. However, I also need the API to have access to this data object (an array of users) once the data becomes available. What is the best way to approach/accomplish this task? The only way I can think of now is to have a setTimeout function that waits for the app to load than uses an http get to grab the data from the url. There must be a cleaner way of accomplishing this task. Heres some code I have working, basically a simple node server running express. I'm somewhat new with building API's and Angular 2 concepts so any help is greatly appreciated.
app.js
/** Dependencies **/
var logger = require('morgan'),
cors = require('cors'),
http = require('http'),
express = require('express'),
errorhandler = require('errorhandler'),
dotenv = require('dotenv'),
bodyParser = require('body-parser');
/** Setup **/
var app = express();
dotenv.load();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(function(err, req, res, next) {
if (err.name === 'StatusError') {
res.send(err.status, err.message);
} else {
next(err);
}
});
if (process.env.NODE_ENV === 'development') {
app.use(logger('dev'));
app.use(errorhandler())
}
/** Requires **/
require('./config/sql.js')(app);
require('./config/routes.js')(app);
/** Port **/
var port = process.env.PORT || 3001;
http.createServer(app).listen(port, function (err) {
console.log('listening in http://localhost:' + port);
});
routes.js
// routes.js
module.exports = function(app) {
var query = require('./query.js')(app);
app.get('/data', function(req, res) {
query.getData(req,res);
});
};
sql.js
var connection = require('express-myconnection');
var mysql = require('mysql');
module.exports = function(app){
app.use(
connection(mysql,{
host : 'localhost',
user : 'root',
password: ‘password’,
port : 3306,
database: ‘my_project’
}, 'request')
);
};
query.js
// DB Queries
module.exports = function(app){
return {
getData: function(req, res) {
req.getConnection(function(err,connection){
connection.query('SELECT * FROM users',function(err,rows){
// console.log("success: ", rows);
res.json(rows);
});
});
}
}
};
user.js
setTimeout(function(){
// http.get function to call to API and grab data and create variable
},500);
// this is where I need an array of users that I get from a mysql database for login and registration logic
var users = [];
I'm not sure I got why you need the Angular code to talk to a different UrL but I would write the server code to take the requests from Angular and then internally reach out to the other API to get the data required. Basically use the node server to act like a proxy to reach the other API.
jfriend00 is right in his comment, this is a question of asynchronous calls.
You are looking for the initial requests to kick off the following: Frontend Request > NodeJS API > Database Query
And the response to fulfill and return promises to create a response chain in the reverse order: Database Response > NodeJS API > Frontend Response
You are probably looking for the angular function $http.get with .then() to perform your frontend calls. But you also need an asynchronous function to request the data from within the API or a database instance, then provide it on an endpoint that the frontend can consume. For that you need a promise or callback in your server-side code as listed in jfriend00's comment.
Consider working on just your NodeJS API until you can achieve the response and requests you need, and build out your frontend with Angular later. The users.js file is a fine endpoint to start on.
I followed a tutorial for a RESTful web app with express:
http://cwbuecheler.com/web/tutorials/2014/restful-web-app-node-express-mongodb/
It showed me how to issue get requests like this:
router.get('/userlist', function(req, res) {
var db = req.db;
db.collection('userlist').find().toArray(function (err, items) {
res.json(items);
});
});
And that makes sense to me. It renders in the jade template, too which is fantastic. Now I'm writing my own app, and it's restful as well. I've come up with the following for my get request
/budget
router.get('/', stormpath.loginRequired, function(req, res, next) {
var db = req.db;
var user_id = req.user.customData["mongo_id"];
var collection = db.get('usercollection');
collection.find({'_id' : user_id}, function (err, user_data) {
res.render('budget', user_data);
});
});
And this renders the template, but I don't think that this will allow me to retrieve JSON from this path later. Is this correct? I have tried putting res.json(user_data); inside the collection.find callback, but it literally only renders json on the page, and I cannot figure out why.
I need the JSON data to be 'GETable' because my other REST methods will be asynchronous, and I will need to use $.getJSON( '/budget', function( data )
I have a server with Node.js and I use Express to build a web app.
My server is already able to get an array from a database using a function (rss_interrogDB). Now I want to use this array to display a list in the html page. But I must be missing something...
On the server-side my code is:
app.get('/', function(req, res) {
rss_interrogDB(function() {
// don't konw what to add here
});
On the html page the code is:
$.get('/', {}, function(data){
// not sure it is the right code
console.log(data);
// then the code to create a list from the array (no pb with that)
});
Thank you for your help!
Assuming your DB gives you an array of data, add something like this to your server code:
app.get('/', function(req, res) {
rss_interrogDB(function(serverData) {
res.send(serverData);
});
});
You could manipulate the serverData object and build one that is more suitable for the client before you send it back, but that depends on what you want to do.
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/