how to use NodeJS pop up a alert window in browser - node.js

I'm totally new to Javascript and I'm wondering how to use node js to pop up a alert window in browser, after sever(Nodejs) received post message from front end?
Do I need to use Ajax?

"after sever(Nodejs) received post message from front end?" show a pop up in the browser. This can not be done. I assume you want to show a popup in if the post request is success. Because you mention about Ajax, This is how it is done.
in your post router definition in the server do it as follows
router.post('/path', function(req, res){
//do something
res.jsonp({success : true})
});
something like this. finally you want to send something form the server to the client. after in the client side javascript file send the post request as follows.
$.ajax({
url:"/url/is/here",
method: "POST",
data : {
data : "what you want to send",
put : "them here"
},
cache : false,
success : function (data) {
// data is the object that you send form the server by
// res.jsonp();
// here data = {success : true}
// validate it
if(data['success']){
alert("message you want to show");
}
},
error : function () {
// some error handling part
alert("Oops! Something went wrong.");
}
});

There is a npm module for popups known as popups. You have to install it using the command npm install popups. Then use it in the following way:
var popup = require('popups');
popup.alert({
content: 'Hello!'
});
You can find more information here

First install the alert module: npm install alert
let alert = require('alert');
alert("message")

This works but there's a catch
it sends alert box like an application does
not like javascript's alert function (that sends you in browser alert popup)

Related

Error: Can't set headers after they are sent - Ajax, Node, Express

I'm trying to using Airtable, node.js, express.js and jquery to create a simple user authentication functionality but I'm fairly new at this and I'm running into a problem I can't seem to fix and the articles I've read I can't seem to grasp or adapt to my particular situation.
I have this Ajax call in my html doc:
$("#checkUser").submit(function(e) {
var studentID = $('input[name="student"]').val()
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
$(window).attr("location", window.location.href + 'Dashboard?student=' + studentID);
},
error: function(data){
console.log("User not found. Try again");
}
});
});
This call sends the inputted username and data to the server which then processes it in the following way:
app.post('/checkUser', urlencodedParser, function(request,response){
var user = JSON.stringify(request.body);
user = JSON.parse(user);
base('RegisteredStudents').select({
filterByFormula: '{UserID} = ' + user.student,
view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
response.sendStatus(200);
});
fetchNextPage();
}, function done(error) {
response.sendStatus(404);
});
});
If the user exists in the database of Airtable, it should send '200' which the Ajax then reacts by redirecting accordingly to the user's profile. Otherwise, if the user does not exist, the server should respond with '404', which the Ajax call should react to by printing a statement in the console. While it does do these two things well, the server breaks down when, after a student puts in the wrong user ID and the Ajax prints the statement, the student tries to put once more a userID. I get the " Can't set headers after they are sent. " message. Please, how can I solve this?
Thank you!
You have two response.send..., you can only send data once. Either make sure only one runs with some conditional or add return before all response.send... so if any of them runs, the program will return and the other response.send.. will not run.

Mock network requests in Cypress

I've been tearing my hair out over this for ages now - and I hope someone can help me :)
I've been trying to stub a network request in Cypress for ages now.
commands.js
Cypress.Commands.add('login', (
email = 'email',
password = 'pass'
) => {
cy.server();
cy.visit('url');
cy.get('input[name="username"').type(email);
cy.get('form').submit();
cy.get('input[name="password"').type(password);
cy.get('form').submit();
});
mock.js
describe('mock', function() {
it('user can login', function() {
cy.login();
cy.get('main[role="main"]');
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
cy.wait('#oppty');
});
});
Chrome dev tools request
Cypress request failed
Any help here would be really appreciated - I've been going crazy!
Thanks so much,
Ollie
Currently, Cypress cy.route can only stub network requests that use XHRs
Native HTML form elements don't use XMLHTTPRequest, hence you cannot use cy.route to stub it.
Most people don't run into this issue because using native HTML forms is not as common nowadays
Edit:
You are also waiting on the route, but haven't actually done anything in your test. Your test should look something like this:
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
// cypress code that would cause a network request.
cy.wait('#oppty');
Also, make sure the request is of type:XHR:
Cypress will only find the network request after it's been aliased. The code in your question indicated you're not doing an action that would cause a network request:
cy.route('GET',
'**/getIncentives*',
{info: {}, results: {}}
).as('oppty');
// cypress expected something to cause a network request here
cy.wait('#oppty');
You should either move the call to route earlier in the test, or move the code that causes the request after the call to route.
Also note that cy.route() may not work with server side rendering (apparently).
I've had this problem when using NextJs, and solved it by first calling some other page, then navigate on the client to the page I actually want to test.
Like so:
describe('test cy.route', function() {
it( 'test 1', () => {
cy.server();
cy.route({
method: 'GET',
url: /.*\/api\/someApiCall/,
response: { 'someApiResponse': 'ok' },
status: 200
} ).as('myRouteAlias');
// go to start page: first page is server side rendered. cy.route doesn't work.
cy.visit('/');
// go to page to be tested: client side, cy.route works then.
cy.get( `a[href="/pageToBeTested"` ).should('exist').click();
// wait for page loaded
cy.url().should('include', 'pageToBeTested' );
// do something that requests '/api/someApiCall'.
invokeFunctionThatDoesTheRequest();
// wait for the request
cy.wait('#myRouteAlias');
});
});

How to open web brower by using AWS post lambda

I have written the piece of code below:
static async postSearchResult(httpContext: HttpContext, injector: Injector) {
const log = injector.get(Log);
const service = injector.get(Service);
try {
let result = await service.redirectToUI(JSON.parse(httpContext.getRequestBody()));
httpContext.ok(result, 200, {'Content-Type': 'application/json'});
} catch (e) {
httpContext.fail(e, 500);
}
}
protected redirectToUI(response: any) {
// If any post api call happened then it should open web browser and pass some field as query parameter
window.open("https://www.google.com?abc=response.abc");
return response ? response : "failed";
}
Here I am getting the following error :
Execution failed ReferenceError: Window is not defined
What am I doing wrong?
What you are trying to accomplish doesn't make much of a sense. Lambda is a back-end service. To open new browser window, you need to use front-end JavaScript, not back-end Node (on the back-end, you have no access to the front-end window object).
If you want to open a new browser window as a reaction to some back-end response, then you can send some indicator in the HTTP response (i.e shouldOpenNewWindow: true as a part of the response object), parse that response on the front-end and it the indicator is present, then you can issue window.open command. But it has to be done on front-end.

How to cancel previous ES request before making a new one

I am using NodeJS with https://www.npmjs.com/package/elasticsearch package
Use Case is like this: When a link is clicked on the page, I will make a request to NodeJS Server which will in turn use the ES node package to fetch the data from ES Server and sends the data back to the client.
The issue is, when two requests are made in quick session(two links clicked in a short span), the Response of first request and then the Response of second request is reaching the client. The UI depends on this response, and i would like to directly show only the second request's response.
So, the question is, Is there any way to cancel out the previous request made to ES Server before starting a new one ?
Code:
ES Client:
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'HostName',
log: 'trace'
});
Route:
app.get('/data/:reportName', dataController.getReportData);
DataController:
function getReportData(req, res) {
query = getQueryForReport(report)
client.search(query)
.then(function(response) {
res.json(parseResponse(response)
})
}
So, the same API /data/reportName is called twice in succession with different reportNames. I would like to send only the second report Data back and cancel our the first request.
If you're only concerned about the UX, rather than stressing your ES, than aborting the ajax request is what you want.
Since you didn't post your client side code, I'll give you a generic example:
var xhr = $.ajax({
type: "GET",
url: "searching_route",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
Remember that aborting the request may not prevent the elasticsearch query from being processed, but will prevent the client from receiving the data.

How to show error message on same page in node js?

I am using post method to submit form in node js. Now when I submit the form, I want to show the error message from node server if login fails. I am setting the message as res.send("") but it is showing message on another window. So please help me to solve this?
You could make an Ajax call from your form to your node server API, then depending on the result from your server, show a message.
Jquery example:
$.ajax({
method: "POST",
url: "/api"
data: {login_data_here}
})
.success(function(msg) {
// redirect to admin area etc
})
.error(function(msg) {
// show login for with a failure message
});
Node API server would return something like this:
res.writeHead(200, { 'Content-Type': 'application/text' });
res.end('Login Success');
Or this on fail:
res.writeHead(400, { 'Content-Type': 'application/text' });
res.end('Login Fail');
You can use this module for persisted flash messages between page redirects - https://www.npmjs.com/package/connect-flash

Resources