Redirect to ''/'' in Node.js + AngularJS - angularjs

I created a project on Node.js + AngularJS I have routes in this project. How I can create redirect to '/' if the user prints whatever link in searching panel.

i would recommend to use ExpressJS as nodeJS framework but via nodeJS you can use the router library to acheive the same.
var finalhandler = require('finalhandler')
var http = require('http')
var Router = require('router')
var router = Router();
//other route urls here
//have this at the end
router.get('/*', function (req, res) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Hello World!');
//or write you logic here.
})
var server = http.createServer(function(req, res) {
router(req, res, finalhandler(req, res))
})
server.listen(3000)
Read in detail about the Router Library
Also read here

Related

socket.io emit not working properly inside express route

I use soket.io in Node.js it's working fine, but there is an issue in the routes files.
Below is my code and flow.
I have server.js file where I define io.
var express = require('express'),
app = express(),
http = require('http').Server(app);
var io = require('socket.io').listen(http);
//io from server.js
io.on('connection', function (socket) {
socket.emit('getDevicePostData', { message : 'Hi from server!!' });
socket.on('sendDevicePostData', function("Hi from server") {});
});
// pass io to routes file
var smart_control = require('./smart_control.js')(io);
app.use('/', smart_control);
And smart_control.js file code is below
module.exports = function(io) {
router.post('/emitdata', function(req, res, next) {
io.sockets.emit('getDevicePostData', { message : 'Hi from route!!' });
});
return router;
}
Above route's emit sometimes work and sometimes does not work.
And this emit is called from angular js. I use https://www.npmjs.com/package/angular-socket-io package in angular
Below code in angular controller:
mySocket.on('getDevicePostData', function(data) {
console.log(data);
});
Here mySocket is factory.
What is wrong in my code. Mainly problem from routes file only.
You just need to replace io.sockets.emit with io.emit.
Here io.sockets.emit will emit to only connected clients and your socket factory might not be up by the time you hit the API.

How to access Node JS route Url in Angular JS site

I am working on a site which is in Angular JS language. Now for website, I have to generate dynamic sitemaps and for this I used Node JS and created a xml.js route in node and wrote hello world.
Now the problem is, I am not able to use access this xml.js in angular site. Here is xml.js code :
var express = require("express");
var router = express.Router();
router.get("/test", function() {
console.log("hello world");
});
module.exports = router;
Here is server.js code :
var express=require('express');
var xml = require("./xml");
var app=express();
app.use('/xml',xml);
app.use('/',express.static('app'));
app.listen(9000) ;
Now whenever I try to access http://192.168.0.19:9000/xml/test I am being redirected to home page always.
Can someone help me out ?
You can try this code.This code work for me
You need to pass req and res parameter.
router.get('/', function (req, res) {
res.send('home page')
})
router.get("/test", function (req, res) {
console.log("hello world");
res.send('test page')
})

MEAN application setup doesn't redirect routes to Angular application

I am trying to setup a base for a MEAN application. I created the new project using Angular CLI, added Express.js, MongoDB modules to the application. In the app.js file I have the following configuration:
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var path = require("path")
var app = express();
var conf = require('./config/conf');
var server = require('http').Server(app);
var mongoDB = require('./adapters/mongodb')
var mongoClient = new mongoDB(conf);
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,__setXHR_');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
mongoClient.connect(function (dbconn) {
app.dbconn = dbconn;
app.conf = conf;
console.log("************************************************************");
console.log(new Date() + ' | CRUD Server Listening on ' + conf['web']['port']);
console.log("************************************************************");
server.listen(conf['web']['port']);
var Routes = require('./routes/http-routes');
new Routes(app);
});
I setup a hello world route for now and no changes done to the angular sources, which means I would land at the Angular default starting page. But I cant land at the page but instead a white screen page. However, I can access the routes using Postman. I do ng build and then node app.js to run the application. What am I doing wrong?
You should use the Express way to handle routes
First
const router=express.Router();
Then let's suppose you have a file using only authentication routes
const authentication = require('./routes/authentication')(router);
To conclude, you only have to do :
app.use('/authentication', authentication);
This allows a better divison of your routes
You 'll use your routes this way
module.exports= (router)=>{
router.get('/',(req,res)=>{
res.json(message:'Hello World');
});
return router;
To set angular routes you need the router module, for more details read the documentation
You serve only index.html from your Angular App. But you need also serve assets, css and javascript. Easiest would be something like this (but you need to adjust directory names:
app.use('/js', express.static(path.resolve(__dirname, 'dist/js')));
app.use('/css', express.static(path.resolve(__dirname, 'dist/css')));
app.use('/assets', express.static(path.resolve(__dirname, 'dist/assets')));

How to create RestFull api with express and node.js?

I am very new to node and express i read some documentation but i did not get any solid understanding how to create rest api with node, So with below basic code i just want to create get api with express and return response to angularjs factory method.I would like to get help and better understanding for the following .
1- How to return response with GET api ?
2- If we have json object how can i pass that data using GET api ?
app.js
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static('./'));
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http',host,port);
});
app.get('/test', function(req, res) {
res.type('text/plain'); // set content-type
res.send('i am a beautiful butterfly'); // send text response
});
workerController.js
$scope.getTestData = function(){
alert('got function working');
workerFactory.getData().then(function(response){
var dataResponse = response.data;
console.log(dataResponse);
})
}
workerFactory.js
angular.module('myApp').factory('workerFactory', function ($http) {
'use strict';
return {
getData: function(){
return $http.get('/test');
}
}
});
For the second part, how to pass a JSON object back. You can change your API code to something like:
app.get('/test', function(req, res) {
res.json({message: 'i am a beautiful butterfly'}); // send a JSON response
});
I'm just working on the first part of the question
You can get a full working REST-full API code by using Amplication, it's an open-source for generating Node.js code by only defining your data model.
As you have the basic understanding on REST API you can use this node module
https://github.com/swagger-api/swagger-node for creating great REST API.

Unable to hit my local API route in Express

I have a server and client folder, inside my client folder I have 2 Angular apps /website and /dashboard
My current routing setup (just for development) going to / will load the website app and views and /dashboard loads the dashboard up:
//website api ==================================================================
var website = express.Router();
app.use('/', website);
app.use('/', express.static("../client/"));
console.log(__dirname + "../client/");
website.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
website.get('/', function(req, res) {
var path = 'index.html';
res.sendfile(path, { 'root': '../client/website/' });
});
//dashboard api ================================================================
var dashboard = express.Router();
app.use('/dashboard', dashboard);
dashboard.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
dashboard.get('/dashboard', function(req, res) {
var path = 'index.html';
res.sendfile(path, { 'root': '../client/dashboard/' });
});
// API to add new accounts:
app.post('/api/accounts/', accountsController.create);
In my dashboard app, the accounts controller I have the following $resource call:
var Account = $resource('/api/accounts');
Which is suppose to hit this API on my server main.js:
// API to add new accounts:
app.post('/api/accounts/', accountsController.create);
However currently getting a 404 on the call
'POST http://localhost:9999/api/accounts 404 (Not Found)'
I think it's the mismatch of trailing slash vs. no trailing slash between your angularjs code and your expressjs code. Try app.post('/api/accounts', accountsController.create);.

Resources