Read data from file and use it on Angular ssr and csr - javascript

I have a config file and I want to use it without HTTP request on angular SSR and then somehow send data to CSR and use it on that too, this config file is a list of links that I want to use in website footer and be able to change them without rebuilding the project or making HTTP request.
The solution I tryed is to read from the config file every 1 hour in server.ts like this:
fs.readFile('./src/skills.txt', 'utf8', (err, data) => {
console.log('updated skills');
if (err) {
console.error(err);
return;
}
if(data) {
skills = data;
}
});
But then for sending this data to response all I could think about which is not really a good way of doing it I guess is to loop around this file and create my output HTML and then replace a key I put in footer HTML with it in returned html as bellow:
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
if(skills) {
html = html.replace('#skills_placeholder',skills);
}
res.send(html);
});
This way I have the output I need in SSR response but I also want to have this response on CSR when user is logged in. I tryed to add an element with and id and select it on CSR but its undefined, Tryed example :
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }, (err, html) => {
if(skills) {
html = html + '<span class="d-none" id="perfectlancer_skills">' + skills + '</span>';
}
res.send(html);
});
And then on CSR I tryed:
this.doc.getElementById('perfectlancer_skills'.innerHTML
but it is undefined althoght it exists on SSR response;

Related

How to Implement MySQL data into an EJS file to make a Profile Page

I am in the middle of a personal project to practice web development better to understand the ins and outs of web development, but I have run into a brick wall. In this personal project, I am creating a profile page. I have successfully linked the MySQL database to my server js file because I can import data to the table, but I am stuck trying to export the data to an ejs file.
I did the following to export the code, but I cannot even call the data because I cannot have SQL locate any entries from login.
app.get('profile', function (req, res) {
console.log("Inside Get Profile");
connection.query('SELECT * FROM ACCOUNTS WHERE PrimaryEmail = ? ', [req.body.email], function(error, results, fields) {
if (error){
console.log("Error");
console.log(error);
} else if (results.length > 0) {
console.log("Data From Get Profile")
console.log(results);
res.render('profile', { data: results });
}})});
So I did the following in an attempt to resolve my issue, which could work, but I am in the matter of pulling the data into the ejs file.
function userProfile(req, res, next){
console.log("Inside userProfile Function");
connection.query('SELECT * FROM ACCOUNTS WHERE PrimaryEmail = ? ', [req.body.email], function(error, results, fields) {
if (error){
console.log("Error");
console.log(error);
next();
} else if (results.length > 0) {
console.log("Data From userProfile Function");
console.log(results);
res.render('profile', { data: results });
next();
}})};
I would call the function at login after.
app.post('/login', userProfile, passport.authenticate('local', {failureRedirect:'/login-faliure', successRedirect:'/dashboard'}));
Any advice on how to get MySQL data to display certain information for the profile page would suffice!
Thank you for your time!
Looks like you've implemented the correct code for passing the parameters to EJS (the first code snippet you showed), so there's no reason something like this wouldn't work.
Hello, <%=data.name%>!
This would be because you passed the user data under "data" here:
res.render('profile', { data: user });
I found out that I had two app.get(‘profile’) method and now the page loads with no error after removing the un-needed one. The next thing I had to do was add the code below after “results.length > 0” and my data would start to show.
user={id:results[0].ID, email:results[0].PrimaryEmail, hash:results[0].EncryptHash, password:results[0].EncryptPassword};
console.log(user);
res.render('profile', { data: user})

Can't get axios to perform get without full url

Every time I try to use /bikes or /bikes/add in my axios requests, it never seems to connect. I always get something like this:
xhr.js:178 GET http://localhost:3000/bikes/ 404 (Not Found)
However, when I use the full url, like: http://localhost:4000/bikes/ it connects perfectly. I tried messing with the app.get in server.js, the get in my route file, and the actually axios.get in my bikes-list file to no avail.
Anyone have any ideas? This is part of a MERN app.
bikes-list.js(component) snippet:
componentDidMount() {
axios.get('/bikes/')
.then(response => {
this.setState({bikes: response.data});
})
.catch(function (error){
console.log(error);
})
}
server.js snippet:
app.use('/bikes', bikeRoutes);
bikes.js(route) snippet:
router.get('/',function(req, res) {
Bikes.find(function(err, bikes) {
if (err) {
console.log(err);
} else {
res.json(bikes);
}
}); });
Thanks!
maybe the cause is that you are not using the right port when using /bikes? One solution is to create a small module like this:
// client.js
var axios = require('axios');
var axiosInstance = axios.create({
baseURL: 'http://localhost:4000',
/* other custom settings */
});
module.exports = axiosInstance;
and then use this new module in your code instead of requiring axios
directly:
var client = require('./client');
client.get('relative/path')

Proper way to send JSON data along with sendFile() with Node.js and Express

I've setup a Node.js server with express and I've setup routing. When navigating to a specific location: "/users/id", I'm currently using sendFile(), but I'd also like to pass JSON data into the page.
I know I can serve the page and then make an ajax request on page load, but it seems like I would want to minimize server side calls as much as possible.
I would like to do something like below, but even if this works I'm not sure how to grab the data from the web page side. (If I'm not making a separate ajax call)
app.get('/'+element+'/:id', (request, response) => {
const id = request.params.id;
pool.query('SELECT * FROM '+element+' WHERE id = ?', id,(error, result)=>{
if(error) throw error;
response.sendFile(path.resolve(__dirname+'/../html/index.html'));
response.json({message: result.name});
});
});
I'd like to return the data and the file and I'd like to know how to grab the data if I send it at the same time as the file.
Since you only need to to accommodate a simple string for the example you've given, you might consider accomplishing this through a response header. While it's not the most conventional approach, it might be the easiest in your case.
app.get('/' + element + '/:id', function(request, response, next) {
let id = request.params.id;
pool.query('SELECT * FROM ' + element + ' WHERE id = ?', id, (error, result) => {
if (error) throw error;
let options = {
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true,
'x-result-message': result.name // your custom header here
}
}
let fileName = path.resolve(__dirname + '/../html/index.html')
response.sendFile(fileName, options, function(err) {
if (err) {
next(err)
} else {
console.log('Sent:', fileName)
}
});
});
});

Download a PDF file in Node and redirect into front end React

Can you help me to download a file in Node.js and redirect page into the front end? I am using MERN stack (Mongo, Express, React, Node).
After authenticating with the Google Auth, I want to download a file in Node, then I want to redirect the page.
router.get(
'/auth/google/callback',
passportGoogle.authenticate('google', {
failureRedirect: '/',
}),
(req, res) => {
try {
var file = 'resume.pdf';
res.download(file, (err => {
if (err) {
console.log(err)
} else {
window.location.href = '/';
}
}));
}
);
I tried this code, but after downloading it's not redirecting page to front end.
(req, res) => {
try {
var file = 'resume.pdf';
res.download(file, (error => {
if (!error) {
window.location.replace("http://stackoverflow.com");
} else {
console.log(error)
}
}));
}
catch {
console.log(error)
}
Since the headers are already sent with the download response, you'll have to go different route than this.
You'll need to change the response yourself.
var data = //filedata
res.set({
Content-Type: 'text/plain',
Location: '/'
});
res.end(data);
Utilize the Location header accordingly for your redirect.
On the client, you'll want to use:
window.location.replace("/headerLocation");
You want to use this on the client after the success of your callback to your download pdf method.
The reason your getting window undefined is because you're attempting to execute this on your nodejs server. The window object exists on the client.

getting data from express server with angular 2

I'm trying to build a small facebook login with angular 2 but well I'm having problem, after logging in the facebook the user would be redirected to /home
app.get('/home', function (req, res) {
res.sendfile(path.join(__dirname, '../', 'views', 'index.html'), { user: req.user});
console.log({ user: req.user});
});
I'm trying to display the user information in angular2 page but I keep getting undefined. console logging the object works fine.
I used the same method with ejs files using res.render
and using this inside the ejs
<%= user.facebook.name %>
and it works fine. I tried to use {{}} in the angular 2 but not working.
any help please?
thanks
I would define this element when bootstrapping your application. Because this hint is only available within your index.html page, I would use the following processing.
Update the file that bootstraps your application:
import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';
export function main(facebookUser) {
bootstrap(AppComponent, [
provide('user', { useValue: facebookUser })
]);
}
Provide this value from the index.html file this way:
<script>
var facebookUser = '<%= user.facebook.name %>';
System.import('app/main').then((module) => {
module.main(facebookUser);
});
</script>
This question could interest you:
Pass Constant Values to Angular from _layout.cshtml
ok thanks for the replies i found the answer for my question. this code will call the api that and get the user details
constructor(private http: Http) { }
ngOnInit() {
this.getUser();
}
getUser() {
this.http.get('/api/user')
.map((res:Response) => res.json())
.do(data => console.log('data: ' + JSON.stringify(data)))
.subscribe(
data => { this.user = data.user.facebook.name},
err => console.error(err),
() => console.log('done')
);
}

Categories

Resources