How to create an Angular module with changeable properties? - javascript

I'm writing an AngularJS module to provide some convenience for interacting with my product's REST API. Since my product is deployed on premise, each user will have to supply their own URL to interact with the API. So, the base URL needs to be configurable.
I've been looking at $http's way of setting default headers to figure out how to make a nice API for configuring such properties, but haven't had much luck. What I'm trying to achieve is something like this:
in my api.js file:
angular.module('myProduct', [])
properties.baseUrl = 'someDefault';
properties.authenticationToken;
authenticate = function(user, pass) {
properties.authenticationToken = $http.get(properties.baseUrl + '/login');
}
in the customer's app.js file:
angular.controller('myController', ['myProduct'], function($myProduct) {
// during initialization
$myProduct.properties.baseUrl = 'customer.com/myProduct';
// either during initialization, or after submitting a login form
$myProduct.authenticate('username', 'password')
.then(/* do some other API call */);
})
My questions are:
How to expose the properties in my module in a nice, configurable way?
How to expose the authenticate function in my module so it can be called from the customer's app.js in a nice way?
Any links to the Angular documentation I might have missed are also appreciated.

One angular way is using providers for module configuration.
Here documentation
Here a nice example
And here 2 fiddle, 1 for using defaultUrl and other for change it from client.
[http://jsfiddle.net/r057c9o5/3/][3]
[http://jsfiddle.net/t5uf9jau/][4]

Related

How to REST call Angular TypeScript Server with JavaScript

I am currently working on a Sessions Server for a company project.
My problem is, I cant find any help to accomplish, that I can do javascript HTTP calls from a javascript server running with http.createServer() and server.listen(8080, ...) to my Angular Server, which is hosted with ng serve running on localhost:4200.
What I want, respectively need,is something like mentioned below in pseudocode:
In my Angular TypeScript file I need something like:
private listdata = new Array<string>();
ngOnInit(){}
constructor(private http: HttpClient){
this.http.listen(method: "POST", address: "http://localhost:4200/data", callback: => (data){
this.listdata = data;}
)
}
So that my Angular Application (Server) can receive REST calls from another Server.
In my JavaScript file I want to do smth. like:
http.post("localhost:4200/data", data, httpOptions);
So in the end, my javascript server running on localhost:8080 sends data to my angular server running on localhost:4200.
I tried to read me through several sources, containing HttpInterceptors etc. but couldnt find a simple solution for Noobs like me.
Is there an easy way, so that my automatically builded and hosted Angular Server can define routes it listens to and process the data directly for frontend use?
Thanks in advance :)
I think you have to read documentation again
In my opinion or am using like that when calling rest.
2.1 Rest function have to write in httpService.service.ts
2.2 Rest I used to HttpInterceptor to login OAUTH it will check auth guards,
then token expired you check easy way.
3. last question: You asking like roles something, you want to show components different users? yes you can manage routing,
https://www.thirdrocktechkno.com/blog/how-to-integrate-interceptor-in-angular-9/

Send headers with Vue-Router

I already searched for a good while on the Internet and even checked all suggested questions here, but I found nothing.
Basically, I'm using vue-router to load views when the user clicks on them (without prefetching, just lazy-loading), using a function that imports the Vue view/component. To better visualize, I made a barebone example of what I'm doing:
const router = new VueRouter({
routes: [
...
{
path: "/a_page",
component: function() {
return import("./views/A_Page.vue");
}
}
]
});
I'm using Express in the backend to protect certain routes, because protecting it in the Frontend is wasted effort, since the user could bypass the 'protection' easily, if he wants to. Also all views have their own splitted .js file (using "webpackChunkName") and Express needs a Bearer Authentication Token header for every API call OR .js file requested. This works great with Axios (responsible for fetching API data) where you can manually define a header, but vue-router hasn't this option, and since it doesn't send the Authorization header, it doesn't authenticate, Express blocks the file with a 403 and vue-router fails to import the file.
Is there any way to send the Authorization header with the import (which is basically just a GET request)?
Thanks in advance.
If someone thinks I'm approaching the problem in a wrong way, feel free to comment and suggest another way.
EDIT: The suggested duplicate question was given too little attention and the only solution given (which is basically split in 2) doesn't work with the current webpack anymore; onload(event) and onerror(event) get undefined.
You could use a router guard instead of protecting with basic auth.
I use this method, along with lazy loaded routes. If the auth fails you can redirect the user to a login page.
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
If (auth) { // get value of cookie etc for a jwt token or similar auth method
next() // proceed
}
else {
next(false) // cancel navigation
// or
next(“/login-url”) // redirect you login url
}
})
Additionally, you could use an axios method to auth on each route change.
If you want to send up the Authorization header (which doesn't seem to be an easy task, given that no one knows how to go about it...) I think you could override webpack's jsonp function that it uses to load the chunks in splitChunks...
Here's the docs for the webpack function that loads the chunks
You'll override your webpack config with your modified chunk loading function and then tie that into your vue.config.js like so...
// vue.config.js
module.exports = {
configureWebpack: require('./webpack.config.js')
}
All this being said, I would suggest protecting your frontend assets much earlier than when you need to be loading your split chunks and not requiring the Authorization header to serve your static assets.
Sometimes you can do this at the network layer (load balancer, etc) depending on your use-case. Other times using a server-based approach, like rendering your app w/ Nuxt, will be what you want.
If I'm understanding correctly (feel free to correct me), would you be able to do an auth call with axios prior to the actual routing, or perhaps upon the routing using a mounted call? Especially if there is no valid authentication you can then either redirect to a login page or re-route to an error page.
Feel free to let me know if I'm misunderstanding.

Multipage Node.js Server Without Routing Bloat?

Can I set up a multipage Node.js web server that does not require a unique route for every page?
I have a simple HTTP server set up using Node and Express, using EJS for view engine. My routing currently looks like this:
// routing
app.get('/', routes.index);
app.get('/hig', routes.hig);
app.get('/proto', routes.proto);
app.get('/design', routes.design);
app.get('/process', routes.process);
app.get('/demo', routes.demo);
app.get('/api', api.index);
app.get('/api/rules', api.list);
app.get('/api/rules/:id', api.ruleid);
I'd like to be able to easily update my site to have pages such as /hig/section1 and /hig/section2 (and so on) without having to update the route table each time and restart the server. More importantly, I'd like to be able to quickly and easily make multiple versions of a demo and be able to link to them.
For example, create a new demo and link a user to /demo/version23 while linking someone else to /demo/version 35, allowing me to illustrate different functionality without breaking previous demo sites. It would not be long until /demo/version108 and beyond exist, so having a sane way to create these without having 108+ routes is preferable.
The only method I've been successful at so far is updating route tables. Is there another way I can point to different pages in the route table that will allow me to more easily add new pages?
You should consider making part of url variable for ex as /hig/:section.
You should then get section as a parameter which you can use to map to different content, page or do any other logic that you want with that.
In my express api, I have a wildcard get. The endpoint var parses the keyword and then whatever you decided to do with that is up to you. In mine I have some if statements to change the database model etc but you don't need that... I would suggest keeping the 404 send, so if somebody hits an undesired url you can just give them whatever status code.
app.get('/:endpoint', function (req, res) {
var endpoint = req.params.endpoint;
if( endpoint == 'something' ){
} else if( endpoint == 'something' ){
} else { return res.send(404, { erorr: "That resource doesn't exist" }); }
// Display the results
});
I implemented simple demo project to achieve multi-app structure.
https://github.com/hitokun-s/node-express-multiapp-demo
With this structure, you can easily set up and maintain each app independently.
I hope this would be a help for you.

AngularJS Module Configuration

Looking for some help with a best practice.
I have a module which I am setting a few custom headers. No big deal here:
$httpProvider.defaults.headers.common['token'] = function() {
return token;
};
token is a value that I must $http.get() on the page load.
My intial thought was to put this in my controller, but after thinking about it, it more more sense to do it in the module configuration on page load where I am setting my custom headers:
var app = angular.module('app',['ngRoute', 'ngResource'],function($httpProvider) {
// Custom headers
});
My question is two part:
Is this the best way to do this?
If it is, how do I make a $http.get() request inside of the module config?
app.config, as you might have noticed, won't allow you to use services like $http (or any service you make yourself), it's run before they are defined. Try putting the call in your app.run instead. It is after config and it has no restrictions against using services.
If it is the right approach or not is harder to answer as it depends on the exact use-case. As $http-calls are asynchronous you cannot just call your backend when the app starts and be sure the token exists in your controllers or services, the http call might not have returned yet! This might be a problem for you if you expect to use the token right away.
A better option, again depending on use-case, might be to use a resolve-function on any route that needs the token. A route will holds off on loading any controller and template until the routes resolve-function has finished. Using this method you can then be 100% sure that the token exists once the controller is run.
This video has a good intro to resolves.
They can also be combined. Running the http-call in your app.run, and then using a resolve function to make sure it exists before the controller loads.

How to use headers for session key rather than a cookie in node's Sails.js

Obviously using cookies makes the most sense for storing the session ID when working with browsers etc, but I'm using Sails just to build up my RESTful API, and I'd like to use a header (X-Session-Identifier or something) to provide the session ID to Sails (this could be returned as a header in the response as well so I know what to then send again).
I assume I need to write some middleware, but I can't find anywhere in the docs where I could hook into.
Do I need to remove connect's cookieSession middleware and replace it with my own?
Sails.js 0.9.x
This is not documented anywhere, but you should be able provide custom middleware to the underlying express object by doing the following:
config/express.js
var sessionware = require('mycoolmiddleware');
modules.exports.express = {
customMiddleware: function (app) {
app.use(sessionware.sessionHeader());
}
};
Sails.js handles this here: https://github.com/balderdashy/sails/blob/v0.9.16/lib/express/index.js#L162
Sails.js 0.10.x
As of Sails.js 0.10.x, they now document how to provide custom middleware here: http://sailsjs.org/#/documentation/concepts/Middleware

Categories