Redirect Express js piped (req.pipe) res properly - express

Probably I'm doing something wrong but:
In my browser I have a code
window.location = '/some/url'
or element with href="/some url"
in node (express.js) I have following route handler:
app.get('/some/url', function(req, res){
res.redirect('http://www.google.com')
});
Content of the page is loaded with strange flaw Google page. And address bar is not changed (http://localhost:3000/some/url).
I'm making request via intermediate server using
req.pipe(request(host + req.url)).pipe(res) and it seems that piped res does not redirect properly. Any ideas how to solve it?

I needed to use {folllowRedirect: false} option for reqest.js

Related

sending POST request to express route - after receiving form data, res.render is not triggered

I'm trying to create a simple app where a picture gets uploaded, and that picture is drawn on html canvas so that i can do some simple pixel manipulation.
Right now I have the GET method for root render an EJS template with a fileReader and a canvas.
With code attached at the bottom of the EJS file through script tags, I draw the uploaded image onto the canvas so I can read each pixel's rgb values.
I then tried to send those rgb values to the POST route in the app (through fetch), but it's not working as expected.
app.post("/", (req, res)=>{
console.log("inside post");
console.log(req.body);
res.render("test", {result: req.body});
console.log("after res.render");
});
All three of the console logs print correctly in the terminal, including the request body, but the test template is not being rendered. It just stays on the same "index" view the app launches with.
Can someone give me some insight as to why this is happening? I also included console logs inside the script tags in the ejs template, and these are only displayed in the browser, not in the terminal I launch the express app with. How can I render the view inside the post method?
First
If you use AJAX like Fetch API or XHR, browser will not render the test page.
Because it's asynchronous, and you could see Ajax in MDN web docs.
You need to use form post with following code.
<form action="/" method="post">
<button type="submit">go to another page</button>
</form>
But, if you use form post, your page which might be "index.ejs" will be replaced with "test.ejs".
In other words,
Browser uses the response from the forms POST request to load the new page.
But browser pass AJAX request's response to a callback and trigger callback in js.
Browser handle these two type request (Form Post and AJAX POST) with different ways.
In common, both are sending data to server.
So, in your case, res.render is triggered successfully.
Let me show you an example. Here is my server code.
const express = require('express')
const app = express()
app.set("view engine", "ejs")
app.get("/", (req, res, next) => {
res.render("test")
})
app.post("/test", (req, res, next) => {
res.render("other-test")
})
app.listen(3000)
<!-- test.ejs -->
<h1>this is test pages.</h1>
<!-- other-test.ejs -->
<h1>this is other test pages.</h1>
When I type url http://localhost:300, browser show me this.
And I open console in chrome and type following code.
fetch("/test", {
method: 'POST', // or 'PUT'
body: JSON.stringify({}), // data can be `string` or {object}!
}).then(res => {console.log("trigger response")})
Then go the network tab in chrome, you will see the request.
Here, this request trigger the express method.
But, what is the response?
Well, it's a html. That means res.render("other-test") is triggered correctly.
And you will find the console output show "trigger response" which callback is triggered in my fetch.
And, page still stay in "test.ejs".
Next, I add following code in my test.ejs
<form action="/test" method="post">
<button type="submit">Go to other page</button>
</form>
Page will be like this.
After you click, you will find out the browser show you "other-test" content.
That's a difference between form post and ajax post.
Second
You put script tag into ejs template.
Express will use ejs engine to render your ejs template become to html page.
After it become to html page, it means all script is running in browser not your nodejs terminal.

Is it possible to accept POST request in vuejs (client-side)?

The code below handles GET request and will display the login page:
const routes = [
{
path: '/',
name: 'root',
component: Login
}
]
I can display data using router with GET method in vuejs. Now, I want accept POST requests/methods from external website. Is it possible? If it is, how should I make it, if not possible, is there another alternative solution for this?
No, that's not possible. Your routes are not even GET requests. You can intercept any request on your own application, but you can't listen for external requests, that's what HTTP servers are for.
No, a client app in a browser cannot accept requests from other websites/services, no matter which HTTP method is going to be used.
If you want for some reason your Vue based application to be accessible remotely then you can consider using SSR.
Pass data via the webpage holding the Vue instance
Yes you can with a trick!
What is your first base file that is loading your vuejs ?
is this an html file like index.html?
try load your vuejs in a php file like index.php and at top of your php file like write this:
<!DOCTYPE html>
<html >
<head>
...
<script >
window.postedData = '<?php echo json_encode($_POST)?>';
</script>
...
</head>
Now you can use your postedData variable every where in your vuejs code
mounted() {
const arr=JSON.parse(postedData)
console.log(arr)
...
}

Open URL from file system using PhantomJS

In page.open I can read about how to open a page using http.
How do use the WebPage module to open an url from the file system?
I have tried to omit http:// and have an url with ../some_dir/foo.html, but it seems to fail.
I Have tried this:
var page = require('webpage').create();
var fs = require('fs');
fs.changeWorkingDirectory('../foo/bar');
page.open('file://index.html', function(status)
{
console.log(status);
//console.log(document.title);
phantom.exit();
});
which outputs "fail".
I got the advice to test an absolute path, trying this:
var page = require('webpage').create();
var fs = require('fs');
page.open('file:///absolute/path/to/index.html', function(status)
{
console.log(page.title);
console.log($('body').length);
phantom.exit();
});
(with and without the call to changeWorkingDirectory, but with the same result)
I get a page title, but phantomjs reports that $ is undefined, jQuery is included in my html file (that is too large to post here). It is included like this:
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
Trying to run functions also produces errors like
CanĀ“t find variable: function_name
Does the page/file you are opening already have jquery embedded on the page? If not, you will need to use either injectJs or includeJs on the page object before you can use the $ operator.
http://phantomjs.org/page-automation.html
If you are just doing a simple DOM selection, I would recommend just calling
document.querySelector('body').length
As these functions already exist within the Phantom instance.

Meteor IronRouter onBeforeAction causes exception in defer callback

I'm trying to secure my meteor app with iron-router, here's my onBeforeAction function:
this.route('manageUsers', {
path: '/panel/user_management',
layoutTemplate: 'panel',
onBeforeAction: function(){
if((Meteor.user() === null)||(Meteor.user().role !== 'superAdmin')){
Router.go('signIn');
throwAlert('You dont have access to see this page', 'notification');
}
}
});
When I'm trying to go to /panel/user_management subpage by pressing a link button everything goes fine (user is redirected etc.), but when I type the path directly in my browser (localhost:3000/panel/user_management) and hit enter user is not getting redirected and I receive in console Exception in defer callback error. Anyone know what I'm doing wrong?
For additional information, this view lists me all users registered. When I go to this path normally (without error) I see complete user list. When I receive error template doesn't appear in > yield.
Finally, I've solved this - the problem was wrong if statement, here's the correct one:
if((!Meteor.user())||(Meteor.user().role !== 'superAdmin')){}

ExtJS4 - How to make an initial entry to a site with param data?

I have an ExtJS4 site www.mysite.com where I serve index.html when a user enter the site. I want the user to be able to access the site with some param data redirected from another site. For example, www.mysite.com?q=10
How do I capture q=10 which I will use to retrieve some data from the database?
How do I send index.html so that browser retrieves javascript and css files. Once all the javascript and css files are loaded, I need to render a page displaying the result from the database?
Thanks
To get the url parameters I've done this :
var getParams = document.URL.split("?");
var params = Ext.urlDecode(getParams[getParams.length - 1]);
console.log(params.q) // you should see 10 being printed
If index.html is gonna come with some param in the url you can use the launch method to do an ajax request and bassed on that response render something
Ext.application({
name : 'MyAppWithDynamicFirstPage',
launch : function() {
var getParams = document.URL.split("?");
var params = Ext.urlDecode(getParams[getParams.length - 1]);
var q = params.q;
Ext.Ajax.request({
url: 'someServlet/getViewToRender',
params: {
'q': q
},
success: function(response, opts) {
//bassed on this you would do something else like render some specific panel on your viewport
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}
});
I hope this was of some help.
Best regards.
Depends of your web server, programming language and architecture
Usually first ExtJs is loading with all js/css. After it loaded, data loads asynchronously from the server. But if you exactly know what are you doing, you can render your data into a global variable inside a script tag and then use it in the code.