Hello I have for this moment a fake backend with httpbackend in my angular Project. But I want to transfer my fake backend in a server node js but I don't know.
So For this moment I have this :
var express = require('express')
, path = require('path')
, fs = require('fs')
, bodyParser = require('body-parser')
, morgan = require('morgan');
var apps = express();
var staticRoot = __dirname + '/';
apps.set('port', (process.env.PORT || 3000));
apps.use(express.static(staticRoot));
apps.use(bodyParser.urlencoded({ extended: false }));
apps.use(bodyParser.json());
apps.use(morgan('dev'));
apps.use(function (req, res, next) {
var ext = path.extname(req.path);
if (ext !== '') {
return next();
}
});
apps.get('/getTpl', function (req, res) {
res.writeHead(200);
res.end(JSON.parse(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]));
});
apps.listen(apps.get('port'), function () {
console.log('serveur en route, port : ', apps.get('port'));
});
My controller :
ctrl.tpls = [];
ctrl.tplJson = undefined;
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data);
console.log(response.data);
});
function getTpl() {
return $http({
method: 'GET'
, url: '/getTpl'
});
I want to send my array in my select but my select is empty why ? please
Thank you so much for your answer
You have to change this function:
apps.get('/getTpl', function (req, res) {
res.status(200).json(["tp1", "tp2", "tp3", "tp4", "tp5", "tp6", "tp7"]);
});
Additionally I do not use Angular, but I don't think that you have to stringify the response:
diapoService.getTpl().then(function (response) {
ctrl.tpls = JSON.stringify(response.data); // <- Is this necessary?
console.log(response.data);
});
Related
NodeJS File server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var moment = require('moment');
var http = require('http');
var jwt = require('jsonwebtoken');
var config = require('./config');
var User = require('./app/models/user');
var port = process.env.PORT || 8080;
mongoose.connect(config.database);
app.set('superSecret', config.secret);
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/onboardAuthentication', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
res.setHeader('contentType', 'application/x-www-form-urlencoded;charset=utf-8;');
res.json(req.body);
});
var server = http.createServer(app);
server.listen(port);
console.log('Magic happens at http://localhost:' + port);
Angular API Hit Code where Front side API hit
var serviceRoot='http://localhost:8080/onboardAuthentication';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
function goodResponse(response)
{
console.log("Good response");
console.log(response);
}
function badResponse(response)
{
console.log("Bad response");
console.log(response.data);
}
It print result in this formate, it make post data as key and value is blank, but i want to access post data in json format using body-parsar node js.
{"key":"value"}: ""
If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work,
by default angular will send application/json to the server.
var req = {
method: 'POST',
url: serviceRoot,
data: { key: 'value' },
// comment this line, you don't need it
//contentType: 'application/x-www-form-urlencoded;charset=utf-8;'
};
I'm learning Nodejs and ExpressJS. I'm trying to use ExpressJS and 2 Node modules (request-ip and geoip2) to get the client IP address for geolocation and then outputting the geolocation in the browser using AngularJS (1.x).
So far for my Nodejs and Expressjs code I have
var express = require('express');
// require request-ip and register it as middleware
var requestIp = require('request-ip');
// to convert the ip into geolocation coords
var geoip2 = require('geoip2');
// Init app
var app = express();
var port = process.env.PORT || 8000;
geoip2.init(); // init the db
//app.use(requestIp.mw({ attributeName: 'myCustomAttributeName'}));
var ip = '207.97.227.239';//67.183.57.64, 207.97.227.239
// respond to homepage req
app.get('/', function (req, res, next) {
//var ip = req.myCustomAttributeName;// use this for live
//var ip = '207.97.227.239';/* use this for testing */
console.log('requestIP is ' + ip);
next();
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
console.log("Error: %s", error);
}
else if (result) {
console.log(result);//ipType was causing console.log duplication, IDK why
}
});
});
// set static folder
app.use('/', express.static(__dirname + '/public'));
app.listen(port, function(){
console.log('user location app is running');
});
And for Angular I have
angular.module('UserLocation', []);
angular.module('UserLocation')
.controller('MainController', MainController);
MainController.$inject = ['$http'];
function MainController($http) {
var vm = this;
vm.result = '';
vm.message = 'Hello World';
vm.getLocation = function() {
console.log();
return $http.get('localhost:8000', {
params: {result: result}
})
.then(function(result){
console.log(result);
})
};
};
vm.result in the Angular controller is for the result from the geoip2 Node module that performs the geolocation.
I can get the result in the console no problem but I'm not to sure how to pass it to Angular. I'm using the $http service but I'm not sure where to go from here...?
How do I pass the result from the geoip2 Node module to my Angular controller with $http?
The problem is that you are calling next before you are even done.
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
Then on angular
$http({
method: 'GET',
url: '/yourURL'
}).then(function (response) {
console.log(response);
});
If you want to use the user IP to get location:
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
I am new to MEAN applications.Here I have a REST based sample application using node-restful library in which I can perform operations(get,save,delete) except 'put'. However 'put' operation works well on rest clients (advanced REST, postman) but not on angular client.
mongoose Model
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
college: String,
age: Number
});
// Return model
module.exports = restful.model('Products', productSchema);
Node-express code
var express = require('express');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors =require('cors');
// MongoDB
mongoose.connect('mongodb://localhost/rest_test');
var autoIncrement = require('mongoose-auto-increment');
// Express
var app = express();
app.use(methodOverride('_method'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./routes/api'));
// Start server
app.listen(4000);
console.log('API is running on port 4000');
angular function to update the data
$scope.updateData = function (userID) {
$scope.actionData = {
"name": $scope.name,
"college": $scope.college,
"age": $scope.age
}
RoleEditF.updateUserData({
userId: userID
}, $scope.actionData).then(function (response) {
$scope.userData = response;
console.log($scope.userData)
$scope.getData();
}).catch(function (response) {
$scope.error = "Unable to get Files (code: " + response.status + "). Please try later.";
});
}
angular.module('myapp')
.factory('RoleEditF', function (updateS) {
return {
updateUserData: function (parm, data, callback) {
var cb = callback || angular.noop;
return updateS.save(parm, data,
function (res) {
return cb(res);
},
function (err) {
return cb(err);
}.bind(this)).$promise;
}
}
})
Factory to call API
angular.module('myapp')
.factory('updateS',function($resource) {
return $resource('http://localhost:4000/api/products/:userId', { userId: '#userId' }, {
update: {
method: 'PUT'
}
}, {
stripTrailingSlashes: false
});
});
I'm getting following error on browser
"NetworkError: 404 Not Found - http://localhost:4000/api/products/57161e0fe4fbae354407baa3"
it has to be 'update' in
'update': {
method: 'PUT'
}
inside your $resource() factory
documentation here
https://docs.angularjs.org/api/ngResource/service/$resource
under Creating a custom 'PUT' request
I'am trying to create a restful api but I need to use an external api quandl to build my api, when i try to use my api from the client(built in angularjs) i get a 500 internal server error and No default engine was specified and no extension was provided in command line. i know my api work cause i tested it with postman, its just not working from the client.
I tried looking at this post : express js 4 how to serve json results without rendering any views /css but it wasnt helpful.
module.exports = function(io){
var q = require('q');
var request = require('request');
var mongoose = require('mongoose');
var Stock = mongoose.model('Stock');
var base_url = "https://www.quandl.com/api/v3/datasets/WIKI/";
var dotjson = ".json"
var apiKey = "?api_key=" + process.env.quandl_apiKey;
function sendJsonResponse(res,status,content){
res.status(status);
res.json(content);
}
// get stock data using quandl api
function stockData(name){
var deferred = q.defer();
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1;
var date = d.getDate();
request({
url: base_url + name + dotjson + apiKey,
qs:{
start_date:(year-1) + '-' + month + '-' + date,
end_date:year + '-' + month + '-' + date
}
},function(error,response,body){
if(error){
deferred.reject('Error: ' + error);
}else if(response.statusCode !== 200){
deferred.reject('Invalid Status Code: ' + response.statusCode);
}else{
deferred.resolve(body);
}
})
return deferred.promise;
}
// get stock data that is stored in database
function getStockInDatabase(req,res){
Stock.find({},function(err,stock){
if(err){
sendJsonResponse(res,404,err);
} else {
sendJsonResponse(res,200,stock);
}
})
}
// create stock data to be stored in database
function createStockData(req,res){
var stockDatas;
stockData(req.body.name.toUpperCase())
.then(function(stock){
stockDatas = JSON.parse(stock);
Stock.create({
name:stockDatas.dataset.name,
symbol:stockDatas.dataset.dataset_code
},function(err,stk){
if(err){
sendJsonResponse(res,400,err)
}else{
sendJsonResponse(res,201,stk);
io.emit('stock',stockDatas);
}
})
})
.catch(function(err){
sendJsonResponse(res,404,err);
})
}
// delete stock data in database
function deleteStockData(req,res){
Stock
.findByIdAndRemove(req.body._id)
.exec(function(err,stock){
if(err){
sendJsonResponse(res,404,err);
}else {
sendJsonResponse(res,204,null);
}
})
}
return {
getStockInDatabase:getStockInDatabase,
createStockData:createStockData,
deleteStockData:deleteStockData
}
}
angular service to use api:
(function(){
'use strict'
angular
.module('app.common')
.factory('stockService',stockService);
stockService.$inject = ['$http'];
function stockService($http){
function getStock(){
return $http.get('/api/stocks');
}
function getStockInDatabase(){
return $http.get('api/stocks/database');
}
function createStock(data){
return $http.post('/api/stocks',data);
}
function deleteStock(data){
return $http.delete('/api/stocks',data);
}
return{
getStockInDatabase:getStockInDatabase,
createStock:createStock,
deleteStock:deleteStock
}
}
})()
app.js configuration
require('dotenv').load();
var express = require('express');
var socketio = require('socket.io');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = socketio();
require('./api/models/db');
var app = express();
app.io = io;
var apiRoute = require('./api/routes/index')(io);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'client')));
app.use('/api', apiRoute);
app.use(function(req, res) {
res.sendFile(path.join(__dirname, 'client', 'index.html'));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500).send({
message: err.message,
error: {}
})
});
module.exports = app;
No default engine specified error comes when you have not specified any content serving engine in express.. for you views or html files.
Try using
app.set('views', 'html page location');
app.set('view engine', 'jade');
You might have to additionally require jade.
This is my controller.js
$scope.saveDetails = function(){
if($scope.editMode == false){
//$scope.hidesave = false;
//$scope.person = "";
console.log("i am in save")
console.log($scope.person);
$http.post('/details',$scope.person).success(function(response){
console.log(response);
refresh();
})
$state.go("itemList");
This is my Route.JS
module.exports = function (app){
console.log("Inside Routes");
app.get('/details', require('./details/details').getDetails);
app.get('/details/:id', require('./details/details').getDetails_id);
app.post('/details', require('./details/details').saveDetails);
app.delete('/details/:id',require('./details/details').deleteDetails);
app.post('/details/:id',require('./details/details').updateDetails);
};
This is my details.js wher actual implementation is :
exports.saveDetails = function (req, res) {
console.log("Hi");
console.log("this is to save: ",req.body);
var person = new req.app.schema.detailsdb(req.body);
person.save(req.body,function(err,docs){
res.json(docs);
console.log("docs: ",docs)
});
};
Here req.body returns undefined when i try to insert data from HTML Page to DB , i have written DB using Mongoose
To parse JSON you need to include the express body-parser module and use it before your routes:
var bodyParser = require('body-parser')
// parse application/json
app.use(bodyParser.json())
// the rest of your routes here.
app.get('/details', require('./details/details').getDetails);
app.get('/details/:id', require('./details/details').getDetails_id);
app.post('/details', require('./details/details').saveDetails);
app.delete('/details/:id',require('./details/details').deleteDetails);
app.post('/details/:id',require('./details/details').updateDetails);
https://github.com/expressjs/body-parser/blob/master/README.md