Send Request To Apache Tomcat (localhost:8080) using GruntJs - node.js

Hi I have some architecture, My front end application I have built using grunt,it running on localhost:3000 nodejs server, My BackEnd Application are in the Apache tomcat server (localhost:8080) . Basically backend application running on spring framework. guys i want to send request from my localhost:3000 to localhost:8080 using gruntjs.
Pls help me.
This is my grunt js file
module.exports = function(grunt){
grunt.initConfig({
concat: {
options: {
separator : '\n\n//--------------------------------------------------\n\n;',
banner : '\n\n//---------------All Js file is here ---------------\n\n'
},
dist :{
src :['components/scripts/*.js'],
dest:'builds/development/js/scripts.js'
}
},
sass : {
dist :{
options:{
style:'expanded'
},
files:[{
src:'components/sass/style.scss',
dest:'builds/development/css/style.css'
}]
}
},
connect:{
server:{
options:{
hostname:'localhost',
port:'3000',
base:'builds/development/',
livereload:true
}
}
},
watch: {
scripts: {
files: ['builds/development/**/*.html',
'components/scripts/**/*.js',
'components/sass/**/*.scss'],
tasks: ['concat','sass'],
options: {
spawn: false,
livereload:true
},
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default',['concat','sass','connect','watch']);
};

To solve your problem you have to write separate node server and register with grunt task.
var http = require('http');
var httpProxy = require('http-proxy');
var server = http.createServer(function(){
httpProxy.createProxyServer({target: 'http://localhost:8080'}).web(req, res);
});
module.exports = function(grunt) {
grunt.registerTask('server', function() {
// this.async(); // run forever
server.listen(8000);// Front End Server Listening Port
});
};

Related

Unable to setup secure connection using greenlock-express

I am trying to use greenlock-express to test serving an app with ssl. I am following the documentation here:
So I have app.js:
"use strict";
// Here's a vanilla HTTP app to start,
// but feel free to replace it with Express, Koa, etc
var app = function (req, res) {
res.end("Hello, Encrypted World!");
};
module.exports = app;
And I have server.js:
"use strict";
var app = require("./app.js");
require("greenlock-express")
.init({
packageRoot: __dirname,
// contact for security and critical bug notices
maintainerEmail: "my_email#gmail.com",
// contact for security and critical bug notices
configDir: "./greenlock.d",
// whether or not to run at cloudscale
cluster: false,
})
// Serves on 80 and 443
// Get's SSL certificates magically!
.serve(app);
I used this command:
npx greenlock init --config-dir ./greenlock.d --maintainer-email
'my_email#gmail.com'
And this command:
npx greenlock add --subject my_website.online --altnames my_website.online
That generated the greenlock.d folder:
config.json
{
"defaults": {
"store": {
"module": "greenlock-store-fs"
},
"challenges": {
"http-01": {
"module": "acme-http-01-standalone"
}
},
"renewOffset": "-45d",
"renewStagger": "3d",
"accountKeyType": "EC-P256",
"serverKeyType": "RSA-2048",
"subscriberEmail": "my_email#gmail.com"
},
"sites": [
{
"subject": "my_website.online",
"altnames": [
"my_website.online",
"www.my_website.online"
],
"renewAt": 1
}
]
}
After I run the app on my VPS, this is what gets logged:
However, when I try to access the app, this is what I see:
I followed the exact steps in the tutorial so I do not see why this doesn't work.
Any thoughts?

Testing API's With React Bundled With Webpack

I'm having trouble trying to run my API's when running my frontend react code. I am using webpack and webpack dev server but the problem seems to be that they run their own server while my apis are run by another. I think I can either make my application run entirely in my express backend but having trouble how or somehow use webpack dev server to run both. my backend express node looks like this
const express = require('express');
const bodyparser = require('body-parser');
const app = express();
require('./api/findMedia.js')(app)
var PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
console.log('server is working : ')
})
my webpack config looks like this. You can ignore my proxy key. I was testing webpack dev server to simultaneously run my express server.
var webpack = require("webpack");
var path = require('path');
module.exports = {
entry: {
app: "./src/app.js"
},
output: {
filename: "build/bundle.js",
sourceMapFilename: "build/bundle.map"
},
devtool: '#source-map',
devServer : {
historyApiFallback : true,
hot : true,
inline: true,
host: 'localhost',
port: 3000,
stats: 'errors-only',
proxy : {
'/api': {
host: 'localhost',
protocol: 'http',
port: 8080
}
}
},
plugins : [new webpack.HotModuleReplacementPlugin({multiStep: true})],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.css$/,
loader: 'style!css'
}
]
}
}
and finally I call it in the front end with a simple post request using axios and inside my componentdidmount
componentDidMount(){
axios({
method: 'post',
url: '/find/media'
}).then((response)=>{
console.log('post request to mongo data from front end a success: ' + response)
console.log(response.data.findArticles)
}).catch((error)=>{
console.log('error'+error)
})
}
webpack-dev-server creates it's own server, like you said. If you want to run both webpack-dev-server and express, then you will need the proxy key in the devServer configuration object.
proxy : {
'/api': 'http://localhost:8080'
}
With your setup, what that would do is proxy any request beginning with /api to http://localhost:8080/api. So from your React code, you would do:
axios({
method: 'post',
url: '/api/find/media'
...
})
which webpack-dev-server would proxy to http://localhost:8080/api/find/media.
If your express router is listening for just '/find/media' the devServer.proxy config object has a rewritePath key.
proxy : {
'/api': {
target: 'http://localhost:8080',
rewritePath: {'^/api' : ''}
}
}
If you want express to handle everything, then I think you can use webpack-dev-middleware.

Hapijs-react-views setup

I'm finding some difficulties to follow the guide for hapijs-react-views package setup (npm hapi-js-react-views).
I can run the server but I only get this error on localhost:3000
{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}
My repo on github is: hapi-react GitHub
My code is:
-routes
--index.js
-views
--index.jsx
-app.js
-package.js
// routes/index.js
exports.index = function(request, reply){
reply.view('index', { name: 'John' });
};
// views/index.js
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
module.exports = HelloMessage;
//app.js
var hapi = require('hapi');
var vision = require('vision');
var path = require('path');
var engine = require('hapijs-react-views')();
// Create a server with a host and port
var server = new hapi.Server();
server.connection({
host: 'localhost',
port: 3000
});
// Register Hapi plugins
server.register(vision, function (err) {
if(err) throw err;
});
var options = { jsx: { harmony: true } };
server.views({
defaultExtension: 'jsx',
engines: {
jsx: require('hapijs-react-views')(options), // support for .jsx files
js: require('hapijs-react-views')(options) // support for .js
},
relativeTo: __dirname,
path: 'views'
});
// Add the route
server.route({
method: 'GET',
path: '/',
config: {
handler: require('./routes').index
}
});
// Start the server
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
//package.json
"dependencies": {
"hapi": "^13.4.1",
"hapijs-react-views": "^0.7.3",
"react": "^15.1.0",
"vision": "^4.1.0"
}
Can you help me?
Thanks in advance.
For anyone who sees this in the future, there's a working example of jsx rendering with vision here: https://github.com/hapijs/vision/tree/master/examples/jsx
I was having this exact issue. The documentation doesn't say but you still require React in your view files. That fixed the problem for me.

How to configure port in browser-sync

I have a gulp task running with browser-sync,by default its running on port 3000 of node.js server.I want to change the default port to any other port like 3010.
var gulp = require('gulp'),
connect = require('gulp-connect'),
browserSync = require('browser-sync');
gulp.task('serve', [], function() {
browserSync(
{
server: "../ProviderPortal"
});
});
/*** 8. GULP TASKS **********/
gulp.task('default', ['serve']);
I am using:
browser-sync version-2.6.1
I tried configuring the gulp task like:
gulp.task('serve', [], function() {
browserSync(
{
ui: {
port: 8080
},
server: "../ProviderPortal"
});
});
But it didnot work.
Answer based on the documentation links (link1, link2).
You are using browser-sync version 2.0+, they have a different recommended syntax. Using that syntax your code could be like this:
// require the module as normal
var bs = require("browser-sync").create();
....
gulp.task('serve', [], function() {
// .init starts the server
bs.init({
server: "./app",
port: 3010
});
});
You specify required port directly in configuration object.

Grunt livereload with node.js application

I have written an application in Node.js (with Express & socket.io) and I would like to use Grunt to compile my client-side stuff with livereload while developing and being connected to Node.js application. How can I do this? (Preferably without running Node.js app in another port and client in another port, because of pathing and cross-domain issues)
I installed also Yeoman and it's using out of the box grunt-contrib-livereload package, but from what I understood it's using Node.js Connect server for serving client-side files, thus being separated from my Node.js application..
Example from Gruntfile.js generated by Yeoman:
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// ... cut some parts
grunt.initConfig({
watch: {
livereload: {
files: [
'<%= yeoman.app %>/*/*.html',
'{.tmp,<%= yeoman.app %>}/styles/*.css',
'{.tmp,<%= yeoman.app %>}/scripts/*.js',
'<%= yeoman.app %>/images/*.{png,jpg,jpeg}'
],
tasks: ['livereload']
}
// ..cut some parts
},
connect: {
livereload: {
options: {
port: 9000,
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app')
];
}
}
}
}
// ..cut some parts
});
grunt.registerTask('server', [
'clean:server',
'coffee:dist',
'compass:server',
'livereload-start',
'connect:livereload',
'open',
'watch'
]);
Not sure if you have solved this question yet, but I have done this by adding my express application as a middleware attached to the 'connect.livereload.options.middleware' option.
However, automatic reloading of server side code doesn't work. For that you could implement a reload friendly server using a simple 'node ./server.js', create a connect middleware that acts as a transparent proxy to your development server, and invoke that within your Gruntfile.js before your standard connect/livereload server starts.
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app'),
require('./server') // your server packaged as a nodejs module
];
}
}
}
}
server.js:
var app = express();
...
// Export your server object.
module.exports = app;
My answer is using Gulp that I am more familiar with, instead of Grunt, but I imagine the same approach would work with Grunt as well.
See my repository (and an older one) and my other answer.
Neither any browser extension nor adding any script to your files is needed.
The solution is based on the gulp-livereload and connect-livereload packages working together. First, you start your live reload listener, and pipe into it any file changes (change * to any more specific node-glob to listen to only specific files):
var gulpLivereload = require('gulp-livereload');
gulpLivereload.listen();
gulp.watch('*', function(file) {
gulp.src(file.path)
.pipe(gulpLivereload());
});
Second, you configure your server to use the listener as middleware via connect-livereload:
var connect = require('connect');
var connectLivereload = require('connect-livereload');
connect()
.use(connectLivereload())
.use(connect.static(__dirname))
.listen(8080);
See the packages for more information on how they work internally.
In the Gruntfile, remove connect:livereload and open from server task.
Add following script in the HTML file
<!-- livereload script -->
<script type="text/javascript">
document.write('<script src="http://'
+ (location.host || 'localhost').split(':')[0]
+ ':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')
</script>

Resources