Hapijs-react-views setup - node.js

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.

Related

POST request not completing on postman

The route with GET method works but the route with the POST method doesn't work. The postman is keep running and doesn't respond with a response.
Here is what I have tried,
import * as hapi from "#hapi/hapi";
const init = async () => {
const server: hapi.Server = new hapi.Server({
port: 3000,
host: 'localhost'
});
server.route({
method: 'POST', // if you change it to GET, it works
path: '/test',
handler: function (request, h) {
const payload = { username: 'testUserNames'};
return payload.username;
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
}
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
What could be the issue? where am I wrong?
i had the same problem and i solved it by downgrading to node v14. for some reason the hapi framework isn't compatible with node v16.

Path to my .html file NPM

I'm trying to host my web page locally using Static file server.
I have a file located in a folder on my Desktop, named index.js, that is going to run this server information.
my code is:
const Path = require('path');
const Hapi = require('hapi');
const Inert = require('inert');
const server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
}
}
});
server.connection({ port: 3000 });
server.register(Inert, () => {});
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: './knox/index.html',
redirectToSlash: true,
index: true
}
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
if you look at the link, I've tried filling in things that will open my index.html file from that code. I'm not sure if I'm pathing to my index.html file correctly. My file is located at desktop/knox(folder name)/index.html, along with all my other files.
I am not able to understand the file structure based on your question. Assuming your file structure is :
|-Desktop
|---index.js
|---knox
|---|---index.html
relativeTo : Gives the base position of the file we will choose in handler.
Change
relativeTo: Path.join(__dirname, './knox') and
handler: {
directory: {
path: './index.html',
redirectToSlash: true,
index: true
}
}

swagger listing api for worknik

I have used swagger-express npm module to configure api-documentation parallel to my server so it help devs to keep track of all apis.
What I have folder structure is
/
/api
swagger/
swagger.json
swagger.yml
/swagger /*Having all the index file and configs as given their like public dir*/
My middle-ware configuration is like this
var swagger = require('swagger-express');
app.use(swagger.init(app, {
apiVersion : '1.0',
swaggerVersion: '1.0',
swaggerURL : '/swagger',
swaggerJSON : 'api/swagger/swagger.json',
swaggerUI : './swagger/',
basePath : 'http://localhost:1222',
info : {
title : 'swagger-express sample app',
description: 'Swagger + Express = {swagger-express}'
},
apis : ['api/swagger/swagger.yml'],
middleware : function (req, res) {}
}));
My server is running at port 1222. Now though the SwaggerUI is loaded successfully but its reading api's from wordnik's domain.
How would it read apis from my swagger.yml
If I am mentioning the swagger.yml then whats the relevancy and use of swagger.json
What is discoverURL in SwaggerUI? If I am mentioning my json path (http://localhost:1222/swagger/) in that it ends with error like 'discoveryUrl basePath must be a URL.'
Is their any way I can list all apis in parallel to server? so It can be tested as well? I want it with swagger.
hey just try this https://www.npmjs.com/package/hapi-swagger
npm install hapi-swagger --save
npm install inert --save
npm install vision --save
const Hapi = require('hapi');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('hapi-swagger');
const Pack = require('./package');
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 3000
});
const options = {
info: {
'title': 'Test API Documentation',
'version': Pack.version,
}
};
server.register([
Inert,
Vision,
{
'register': HapiSwagger,
'options': options
}], (err) => {
server.start( (err) => {
if (err) {
console.log(err);
} else {
console.log('Server running at:', server.info.uri);
}
});
});
server.route(Routes);

React + Gulp + Babelify

I am trying to convert my working app from React and Gulp with ES5 to React + Gulp and ES6.
I only tried to replace reactify with babelify but i am still getting gulp error: Illegal import declaration
Here is my gulpfile.js:
"use strict";
var gulp = require('gulp');
var connect = require('gulp-connect'); //Runs a local dev server
var open = require('gulp-open'); //Open a URL in a web browser
var browserify = require('browserify'); // Bundles JS
var source = require('vinyl-source-stream'); // Use conventional text streams with Gulp
var concat = require('gulp-concat'); //Concatenates files
var lint = require('gulp-eslint'); //Lint JS files, including JSX
var babelify = require("babelify");
var config = {
port: 9005,
devBaseUrl: 'http://localhost',
paths: {
html: './src/*.html',
js: './src/**/*.js',
css: [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/bootstrap/dist/css/bootstrap-theme.min.css',
'node_modules/toastr/toastr.css'
],
dist: './dist',
mainJs: './src/main.js'
}
}
//Start a local development server
gulp.task('connect', function() {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true
});
});
gulp.task('open', ['connect'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/'}));
});
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('js', function() {
browserify(config.paths.mainJs)
.transform(babelify)
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('css', function() {
gulp.src(config.paths.css)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'));
});
gulp.task('lint', function() {
return gulp.src(config.paths.js)
.pipe(lint({config: 'eslint.config.json'}))
.pipe(lint.format());
});
gulp.task('watch', function() {
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.js, ['js', 'lint']);
});
gulp.task('default', ['html', 'js', 'css', 'lint', 'open', 'watch']);
and this is my js file (main.js):
"use strict";
var React = require('react');
var Router = require('react-router');
var routes = require('./routes');
import React from 'react';
Router.run(routes, function(Handler) {
React.render(<Handler/>, document.getElementById('app'));
});
Thanks a lot
You need to install babel preset
npm i babel-preset-es2015 --save-dev
and add config to .babelrc like this
{
"presets": [
"es2015"
]
}
Or it's better to use gulp-babel
$ npm install --save-dev gulp-babel babel-preset-es2015
const gulp = require('gulp');
const babel = require('gulp-babel');
gulp.task('default', () => {
return gulp.src('src/app.js')
.pipe(babel({
presets: ['es2015']
}))
.pipe(gulp.dest('dist'));
});
https://www.npmjs.com/package/gulp-babel

Send Request To Apache Tomcat (localhost:8080) using GruntJs

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
});
};

Resources