I can't get the param of the URL which I pass when changing the state in Angular (ui router):
.state('contact.detail', {
url: '/:contactId',
templateUrl: 'detail.html',
controller: 'DetailController'
})
In Express I define an API, but the problem is in getting the param from the URL which I passed from ui router (above).
server.js
var express = require('express');
var mysql = require('mysql');
var url = require('url');
var app = express();
app.use('/', express.static('../app'));
app.use('/bower_components', express.static('../bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "",
database : "db",
multipleStatements: true
});
app.get('/:id', app.urlencodedParser, function(req,res){
var id = req.params.id;
console.log(id); // => :id instead of value
connection.query('SELECT * FROM contacts WHERE contactId = ?', [id], function (error, results) {
if(error) {
throw error;
}
else {
res.end(JSON.stringify(results));
}
});
});
server.listen(3000, function () {
'use strict';
});
In log I get ":id" instead of the real value, for example "45".
I can access the API manually
Please take a look at the plunker for states details.
Since u are using ui-router (or ngRoute) , it is client side routing , if you want to call a route from your server you have to make a http call , with $http service (or $resource) , like:
//this is a example not tested.
.controller('DetailController', function($scope, $stateParams,$http){
console.log('Passed parameter contact id is:', $stateParams.contactId);
$scope.selectedContactId = $stateParams.contactId;
$http.get("localhost:3000/"+$stateParams.contactId)
.success(function(data){
//console.log(data)
})
.error(function(error,status){
})
});
Related
I have an AngularJS app that is connected to MongoDB. I have articles that I am pulling from the database that is then ng-repeated onto an article page. I have a button with Read More... that takes the user to the specific article. When the single article view becomes active I make a get request to the database to get the article._id. The get request is only working on page reload and not when I activate the view. See code below...
AngularJS Controller
app.controller('ArticleViewController', ['$scope', '$location', '$http', '$routeParams', '$window', function($scope, $location, $http, $routeParams, $window){
// $window.location.reload();
let id = $routeParams.id;
console.log(id);
$http({
cache: true,
method: 'GET',
url: '/:id'
params: { id }
}).then(function successCallback(res) {
$scope.article = res.data;
}).catch(function errorCallback(err) {
if (err) {
alert('THERE WAS AN ERROR WITH THE DATABASE');
}
});
}]);
The interesting thing is that I am getting the routeParams.id so part of the controller is working. Also, when I uncomment the $window.location.reload the article loads but it just loads the JSON object into the browser window. Thank you in advance for any help.
Routing with Express and Mongoose Schema
router.get('/:id', function(req, res, next){
Article.findById(req.params.id, function(err, article){
if(err) {
return err;
} else {
console.log(article);
res.json(article);
}
});
});
Mongoose Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var articleSchema = new Schema({
image: String,
title: String,
about: String,
article: String,
id: String
});
var Article = mongoose.model('Article', articleSchema);
module.exports = Article
Nodejs w/Express
'use strict'
const express = require('express');
const path = require('path');
// const api = require('api');
// const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');
const request = require('request');
const mongoose = require('mongoose');
// const logger = require('morgan');
const env = require('./env');
const routeMw = require('./public/middleware/routing.mw');
let article = require('./public/routes/article')
let guide = require('./public/routes/guide')
const app = express();
const clientPath = path.join(__dirname, "./public");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/article', article);
app.use('/guide', guide)
app.use('/article/:id', article);
You have syntex error problm in http request.
You have need to change in parms paramiter i think show.
app.controller('ArticleViewController', ['$scope', '$location', '$http', '$routeParams', '$window', function($scope, $location, $http, $routeParams, $window){
// $window.location.reload();
let id = $routeParams.id;
console.log(id);
$http({
cache: true,
method: 'GET',
url: '/:id'
params:{"id": id}
}).then(function successCallback(res) {
$scope.article = res.data;
}).catch(function errorCallback(err) {
if (err) {
alert('THERE WAS AN ERROR WITH THE DATABASE');
}
});
}]);
I am getting a 404 error while trying to create a new JSON file locally.
Here is my service:
eventsApp.factory('eventData', function($resource){
var resource = $resource('/data/event/:id', {id:'#id'});
return {
getEvent: function() {
//return $http({method: 'GET', url:'/data/event/1'});
//return $resource('/data/event/:id', {id:'#id'}).get({id:1});
return resource.get({id:1});
},
save: function(event) {
event.id = 999;
return resource.save(event);
}
}
});
The web.server js code is as below:
var express = require('express');
var path = require('path');
var events = require('./eventsController');
var bodyParser = require('body-parser');
var app = express();
var rootPath = path.normalize(__dirname + '/../');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(rootPath + '/app'));
app.get('/data/event/:id', events.get);
app.post('/data/event:id', events.save);
app.listen(8000);
console.log('Listening on port 8000...');
The get function works perfectly fine, but the post always throws a 404 error.
See a screenshot below:
What am I missing?
As said in comments, your Express server routes are bad defined.
So when trying to POST data on /data/event/999, no route is defined for.
app.get('/data/event/:id', events.get);
app.post('/data/event/:id', events.save); // You forgot '/' here
I'm trying to authenticate a user based on values entered in a given form. However, after using res.send(), the function at AngularJS controller is not able to correctly redirect user even if the password and username are correct. Am I handling the callbacks correctly?
Controller
<script>
var app = angular.module('myApp', []);
app.controller("loginController", function($scope,$http) {
$scope.sub = function() {
var config = {
headers : {
'Content-Type': 'application/x-www-form-
urlencoded;charset=utf-8;'
}
}
$http.post('/login', { data:{ username: $scope.username,
password: $scope.password} })
.then(function(response){
if(response.state==0){
console.log('Error!');
} else if(response.state==1){
console.log('action on success');
window.location.href = '/views/success.html';}
}).catch(function(error){
console.log('action on error');
});
Authentication
var db = require('../../config');
exports.login = function(req,res){
var username = req.body.data.username;
var password = req.body.data.password;
db.query('SELECT * FROM users WHERE username = ?',[username], function
(error, results, fields){
var result = "0";
if(error) {
console.log('Code 400, Error ocurred');
}
else{
if(results.length>0){
if(results[0].password == password){
console.log('Code 200, login sucessful');
res.json({ state : 1});
}
}
else{
console.log('Code 400, Password or username invalid');
res.json({ state: 0})
}
}
});
}
server.js
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var db = require('./config');
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(express.static(__dirname + '/app'));
require('./app/routes')(app);
app.listen(3000,function(err){
if(err){
console.log(err);
}
else{
console.log("Listening on port 3000");
}
});
Route.js
var auth = require('../app/middleware/authenticateUser');
module.exports = function (app) {
app.get('/',function(req,res){
res.sendFile(__dirname + '/views/index.html');
});
app.post('/login', function(req, res){
auth.login(req,res);
});
}
Thanks in advance!
You need to inject $window in your controller and then in your successful response
$window.location.href = '/views/success.html';
Although using the $window service is considered AngularJS best practice, I don't think this is where the problem is.
Have you tried console.log() the response object of the $http call?
Maybe the problem is because you put if(response.state) instead of if(response.data.state).
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
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);
});