Let's say I have a function which ends with a response.redirect('/'). How can I parse a message along which is shown on that path? Here is a breift example:
expressApp.post("/test", function(request, response) {
if (user) {
response.redirect('/')
}
}
There is more to the function but this is enough for the question here. How can I parse a message or some text to the path "/" and display it in my view?
There isn't a way to pass on data (messages) through redirections other than the use of sessions. You need to set variables in the sessions and access them in another page. For simplicity, these messages are referred to as flash messages. You can use flash messages using the module express-flash. There are solid tutorials on Google and everywhere else, they should be highly helpful.
Your code when using express-flash:
expressApp.post("/test", function(request, response) {
if (user) {
req.flash('mymessage','hello from route');
response.redirect('/');
}
})
In another route file, simply use
expressApp.post("/", function(req,res) {
res.send(req.flash('mymessage')); // Will show "hello from route"
})
Related
I'm moving my existing project written on Express.js to Nest.js and one of the most pressing problem is to serve static html page for changing user's password. I've been looking for any answer for a couple of days, unsuccessfully. My implementation on Express.js works perfectly, here it is:
resetPass.use(express.static(__dirname + "/reset_pass_page"));
resetPass.get("/:id", async (req, res) => {
try {
// here I check ID which is JWT and if everything is OK I send the form:
res.status(200).sendFile(__dirname + "/reset_pass_page/index.html");
}
And now I'm trying to reach the same outcome using Nest.js. I got one single module for resetting password and sending links to user's email. Here is the controller:
#Controller('users/resetpass')
export class ResetPassController {
constructor(private readonly resetPassService: ResetPassService) { }
// here is others routes for getting reset link on user's email and etc...
// in this part I'm sending the form:
#Get("requestform/:id")
sendResetPasswordForm(#Param("id") resetToken: string) {
return this.resetPassService.sendResetPasswordForm(resetToken)
}
}
And what should I do in the service in my case?
async sendResetPasswordForm(resetToken: string) {
try {
// checking resetToken and if it's OK send form like:
res.sendFile(__dirname + "/reset_pass_page/index.html");
What method should i use in that case?
}
}
I've already tried to use ServeStaticModule in my reset pass modle, but I can't make it work properly with dynamic routes. I've tried this config:
ServeStaticModule.forRoot({
rootPath: join(__dirname, '../../../static/resetpass'),
renderPath: /(\/users\/resetpass\/requestform\/)([\w-]*\.[\w-]*\.[\w-]*)/g,
}),
I can make it work for routes without ID, like users/resetpass/, but I need to these page be available only for routes like users/resetpass/:id.
I'm looking forward for any help and advice. Thanks!
Similarly to what you did in Express.js:
res.status(200).sendFile(__dirname + "/reset_pass_page/index.html");
You can also use .sendFile in Nest.js
#Get("requestform/:id")
sendResetPasswordForm(#Req() req: Request, #Res() res: Response) {
const resetTokenPath = this.resetPassService.sendResetPasswordForm(pararms.id)
res.sendFile(join(__dirname, resetTokenPath, '/reset_pass_page/index.html'));
}
You have to add a couple of decorators and types from Express:
import { Controller, Get, Res, Req } from '#nestjs/common';
import { Response, Request } from 'express';
I am new to electron.js - been reading the documentation and some similar post here:
How do I make a database call from an Electron front end?
Secure Database Connection in ElectronJS Production App?
Electron require() is not defined
How to use preload.js properly in Electron
But it's still not super clear how to properly implement a secure SQL integration. Basically, I want to create a desktop database client. The app will connect to the remote db and users can run all kind of predefined queries and the results will show up in the app.
The documentation says that if you are working with a remote connection you shouldn't run node in the renderer. Should I then require the SQL module in the main process and use IPC to send data back and forth and preload IPCremote?
Thanks for the help
Short answer: yes
Long answer:
Allowing node on your renderer poses a big security risk for your app. It is best practices in this case to create pass a function to your preloader. There are a few options you can use to do this:
Pass a ipcRenderer.invoke function wrapped in another function to your renderer in your preload. You can then invoke a call to your main process which can either send info back via the same function or via sending it via the window.webContents.send command and listening for it on the window api on your renderer. EG:
Preload.js:
const invoke = (channel, args, cb = () => {return}) => {
ipcRenderer.invoke(channel, args).then((res) => {
cb(res);
});
};
const handle = (channel, cb) => {
ipcRenderer.on(channel, function (Event, message) {
cb(Event, message);
});
};
contextBridge.exposeInMainWorld("GlobalApi", {
invoke: invoke,
handle:handle
});
Renderer:
let users
window.GlobalApi.handle("users", (data)=>{users=data})
window.GlobalApi.invoke("get", "users")
or:
let users;
window.GlobalApi.invoke("get", "users", (data)=>{users=data})
Main:
ipcMain.handle("get", async (path) => {
let data = dbFunctions.get(path)
window.webContents.send(
path,
data
);
}
Create a DB interface in your preload script that passes certain invocations to your renderer that when called will return the value that you need from your db. E.G.
Renderer:
let users = window.myCoolApi.get("users");
Preload.js:
let get = function(path){
let data = dbFuncions.readSomeDatafromDB("path");
return data; // Returning the function itself is a no-no shown below
// return dbFuncions.readSomeDatafromDB("path"); Don't do this
}
contextBridge.exposeInMainWorld("myCoolApi", {
get:get
});
There are more options, but these should generally ensure security as far as my knowledge goes.
simple question
In end2end testing I want to check a few options, inner texts and links on yopmail in one of incoming mails. The problem occurred after .click on button "Check Inbox" with 404 result.
I looks like yopmail is successfully preventing automated testing.
Am I right, or there is a secret way to do it? and if answer is no, maybe you have some idea how to accomplish test where temporary mails have to be inspected
I'm not familiar with yopmail, but if all you care about is the contents of the email message, perhaps you could forward emails to a provider that doesn't block automation, such as protonmail, and check the contents there? Protonmail doesn't block me from checking/sending emails.
Secret Way :) (works in chrome only, fails in firefox):
You go into the inbox directly by appending it to the URL.
import { Selector } from 'testcafe'
fixture`yopMail`
.page`http://www.yopmail.com?emailme1997#yopmail.com`
.before(async t => {
})
.beforeEach(async t => {
await t.setTestSpeed(0.3)
await t.maximizeWindow()
})
test("hello", async t => {
const chkMail = Selector('.slientext')
await t.wait(3000)
await t.click(chkMail);
await t.wait(5000)
});
async No response On the server side, 200ok comes in, but I can't get it.
I've tried the watch method, but don't. I want to solve it asynchronously.
async mounted() {
try{
let response =await axios.get('http://localhost:5000/process')
this.msg = response
}
catch (err) {
// eslint-disable-next-line
console.log(err)
}
}
};
There is no reaction.
An axios response will contain a number of properties what you are likely looking for is response.data try that and you should have your response assuming you are actually getting something. You can always look in the network tab to see exactly what is coming in even if it not showing on your app, just look for the call and see what the response or preview show.
In the event that your data is not updating in the template you would need to create a key on the element that needs to update to force a rerender, this is because vue's reactivity only works (or mostly) with primitive values not nested structures.
I'm using serverless and https://github.com/horike37/serverless-step-functions to try and implement a system that is hit by a user, returns HTML based on a database entry for the params provided and then moves to a second function that writes to the database (without forcing the user to wait).
I think a step function in the right approach but I can't seem to get it to return HTML - it always returns a JSON body with the executionArn and startDate. e.g.
{
"executionArn": "arn:aws:states:us-west-2:.......etc...",
"startDate": 1513831673.779
}
Is it possible to have my html body return? At the moment my lambda function returns a simple h1 tag:
'use strict';
module.exports.requestHandler = (event, context, callback) => {
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html'
},
body: `<h1>Success!</h1>`,
};
callback(null, response);
};
This is the state machine I'm aiming to create.
I would suggest going for a react/angular/vue frontend hosted e.g. on S3/CDN that uses serverless for backend queries only, instead of rendering dynamic HTML through Lambdas. The 'standard' approach allows you to build apps that are much more responsive and can benefit from e.g. CDNs.
See e.g. https://www.slideshare.net/mitocgroup/serverless-microservices-real-life-story-of-a-web-app-that-uses-angularjs-aws-lambda-and-more or https://serverless-stack.com/