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')
})
Related
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
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.
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.
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);.
I am unable to load view using "$location.path"
Although my browser URLis getting updated but my content is not getting loaded. Here is the controller code:
var app= angular.module("LoginModule",[]);
app.controller("LoginController",['$scope','$http','$location',function($scope,$http,$location){
$scope.submitForm= function(valid){
if(valid){
$http.get('/admin/dashboard').success(function(data){
$location.path('dashboard');
});
}
};
}]);
It is changing my URL to "http://example.com/admin#/dashboard" for the same page.
My router file code is:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/admin', function(req, res) {
res.render('admin/login', { title: 'Login' });
});
router.get('/admin/dashboard', function(req, res) {
//res.render('admin/dashboard', { title: 'Welcome to dashboard' });
res.send("success");
});
module.exports = router;
Please advise I am doing anything wrong.
Per the AngularJS docs at https://docs.angularjs.org/api/ng/service/$location :
Note: Path should always begin with forward slash (/), this method
will add the forward slash if it is missing.
so, you need to put the full value in there:
$location.path('/admin/dashboard');
instead of
$location.path('dashboard');