how do correctly the routing
Client:
controller
$scope.exportData = function () {
$http.get('/api/customers/excel/');
};
Server:
controller
var Customer = require('./customer.model');
var excelReport = require('excel-report');
var express = require('express');
var _ = require('lodash');
var fs = require('fs');
// Get list of customers
exports.index = function(req, res) {
Customer.find(function (err, customers) {
if(err) { return handleError(res, err); }
return res.json(200, customers);
});
};
//calling with index
exports.excel = function(req, res) {
console.log('test export');
console.log(__dirname + 'client/template.xlsx');
var template_file ='template.xlsx';
res.download(template_file);
});
};
index (index routes)
var express = require('express');
var controller = require('./customer.controller');
var router = express.Router();
router.get('/', controller.index);
router.get('/excel', controller.excel);
module.exports = router;
routes.
module.exports = function(app) {
// Insert routes below
app.use('/api/customers', require('./api/customer'));
app.use('/api/things', require('./api/thing'));
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
}
i use generator-angular-fullstack for creating project to test
but I have the following error
GET http://localhost:9000/api/customers/excel/ 500
helpme please
Related
personalinfo.js
var express = require("express"),
router = express.Router(),
personalinfo = require("../models/personalinfo");
// To show PersonalInfo
router.get("/new", function(req, res) {
res.render("personalinfo/new");
});
// To create personalInfo date
router.post("/new", function(req, res) {
const personalInfo = req.body.personalinfo;
console.log(personalInfo);
personalinfo.create(req.body.personalinfo, function(err, ninfo) {
if (err) {
res.send(err);
} else {
res.redirect("/objective/new");
}
});
});
module.exports = router;
obj.js
var express = require("express"),
router = express.Router(),
objective = require("../models/objective");
router.get("/new", function(req, res) {
res.render("objective/new");
});
router.post("/new", function(req, res) {
objective.create(req.body.objective, function(err, nobj) {
if (err) {
res.send(err);
} else {
res.send(nobj);
}
});
});
module.exports = router;
From the personalinfo.js route file I want to use the personalInfo variable in obj.js route file. How can I do that. Thanks for helping me. :)
You can use a module in node.
npm install connect-flash
var express = require('express');
var flash = require('connect-flash');
var app = express();
app.use(flash());
app.get('/login', function(req, res){
req.flash('profileInfo', 'SomeText')
});
app.get('/profile', function(req, res){
let message = req.flash('profileInfo')
res.render('index', { message: message });
});
More info about NPM package
I am trying to access token variable in another page(api.js), how can I use?
index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
var token = req.url;
});
module.exports = router;
module.exports.token1 = token;
api.js [ I want to use token variable in api.js, like this sessionId: requestd.token1 ]
var apiai = require('apiai');
var requestd = require('./index');
var app = apiai('-my-api-key');
var getRes = function(query) {
var request = app.textRequest(query, {
sessionId: requestd.token1
});
const responseFromAPI = new Promise(
function (resolve, reject) {
request.on('error', function(error) {
reject(error);
});
request.on('response', function(response) {
resolve(response);
});
});
request.end();
return responseFromAPI;
};
module.exports = {getRes}
Try
index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
require('./api').get(req ,res) // Be sure your path is correct
});
module.exports = router;
api.js
var api = {
get: function(req, res){
var token = req.url;
console.log(toaken);
}
}
module.exports = api
please update require file statement var requestd = require('./index.js');
and also define "token" variable before this statement module.exports.token1 = token;
I have this code:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
module.exports = router;
Whenever I access URL API/values I receive the data in JSON format, however, I would like to add the ability to access API/values/1 and get only the first row of the data variable. Do I need to add a second router.get like that?
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
router.get('/:id', function(req, res, next) {
res.send(data);
});
module.exports = router;
And how exactly can I print only the first row from the JSON variable instead of all 3?
You could do it like this:
var express = require('express');
var router = express.Router();
var db = require('../helpers/db');
var data = {
"word1": 1,
"word2": 2,
"word3": 3
}
router.get('/', function(req, res, next) {
res.send(data);
});
router.get('/:id', function(req, res, next) {
var key = 'word' + req.params.id;
res.send({ [key]: data[key] });
});
module.exports = router;
However I would consider changing your data structure to something more sensible. perhaps the following would be a good start:
var data = [
{ word: "1" },
{ word: "2" },
{ word: "3" }
];
In the code below I want to restrict access to the 'restrictedRoutes' routes without authorization. But in this case 'restrictedRoutes' affects on any routes excluding 'router'.
For example, if I try to access to the '/test', I want to get 404 error, but instead I'm getting JWT-error about invalid token, If that not provided.
How I can create middleware, that will affects only on routes that provided by certain 'Router'?
/*
* API Routes file
*/
var jwt = require('jsonwebtoken');
var router = require('express').Router();
var restrictedRouter = require('express').Router();
module.exports = function (express, app) {
//Default routes
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
express.use(router);
express.use(restrictedRouter);
};
Mount the router to some path you want to be restricted.
app.use('/restricted', restrictedRouter);
Also I'd avoid the confusion of passing along express and app like you are doing and instead do it like this:
index.js
var express = require('express');
var app = express();
var routes = require('./routes');
app.use('/restricted', routes.restrictedRouter);
app.use(routes.router);
routes.js
var express = require('express');
exports.router = express.Router();
exports.restrictedRouter = express.Router();
router.get('/login', app.controllers.HomeController.login);
restrictedRouter.use(function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
//Restricted routes
restrictedRouter.get('/', function (req, res) {
res.send('Success');
});
Your other option is to use the middleware per route:
var authMiddleware = function (req, res, next) {
try {
var tokenArray = req.headers.authorization.split(' ', 2);
if (jwt.verify(tokenArray[1], 'shh'))
next();
} catch (exception) {
res.status(401).json({error: exception.message});
}
});
router.get('/', authMiddleware, function(req, res) {
res.send('Success');
});
I am trying to implement a search functionality for my app. I have an express route to get incoming search terms.
Here is the entirety of my router file:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var searchutil = require('../utils/searchhandler');
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
var term = req.body.searchTerm;
console.log(term);
searchutil();
res.json({test: 'post received'});
});
module.exports = router;
And here is my searchhandler file which is being including in my router:
var fs = require('fs');
var findResults = function() {
var items = fs.readFile('./server/assets/items.json', 'utf8', (err, data) =>{
if (err) throw err;
console.log(JSON.parse(data));
return JSON.parse(data);
});
}
module.exports = findResults;
This is all working just fine and dandy. it basically just prints out the contents of './server/assets/items.json' on the server when a post request route of '/api/search' is hit. The question I had was about using the json file within my router file. Say my router file was:
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var fs = require('fs');
var items = fs.readFile('./server/assets/items.json', 'utf8', (err, data) =>{
if (err) throw err;
console.log(JSON.parse(data));
return JSON.parse(data);
});
router.use( bodyParser.json() );
router.use(bodyParser.urlencoded({
extended: true
}));
router.post('/api/search', (req, res, next) => {
var term = req.body.searchTerm;
console.log(term);
console.log(items);
res.json({test: 'post received'});
});
module.exports = router;
So now my router file is getting the file asset and trying to print it out within my router.post('/api/search', ...); function. The problem that occurs is that when it attempts to print it in that function items appears to be undefined, but the print from within the fs.readFile(); correctly logs the contents of the file. I think this is some sort of scope issue I am running into with JS, but I am not sure how to explain it to myself so I thought I'd ask it here why it is working one way, but not the other.
You should use a callback:
var getItems = function(cb) {
fs.readFile('./server/assets/items.json', 'utf8', (err, data) {
if (err) cb({error: err});
console.log(JSON.parse(data));
cb({items: JSON.parse(data)});
});
};
And then change the route to:
router.post('/api/search', (req, res, next) => {
var term = req.body.searchTerm;
console.log(term);
getItems(function (cb) {
if (!cb.error) {
console.log(cb.items);
res.json({test: 'post received'});
}
});
});