Path to my .html file NPM - node.js

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

Related

504 Error during the Proxying of Angular with NodeJS inside it

Currently we are trying to run the nodejs server in angular application(net core -angular -spa).We went through this source-
https://www.simplilearn.com/tutorials/angular-tutorial/what-is-angular-node
As per the project we went on creating the angular application and set the proxy based upon the link : https://angular.io/guide/build#proxy-multiple-entries
The Step we are following this:
Step 1: Creation Node Server, which is working individually.
The 504 error shows here.
var express = require('express');
var app = express();
app.use(express.static("myApp")); // myApp will be the same folder name.
// PORT
const port = process.env.PORT || 8000
app.get('/', (req,res) => {
res.send('App Works !');
});
app.get('/externalapi/get', (req, res) => {
console.log(req);
console.log('App Works !');
res.send('Got Files!');
return "Got Files";
});
app.listen(port, () => {
console.log(`Server listening on the port no.:${port}`);
});
Step 2 : Proxy.config.js (not json)
const PROXY_CONFIG = [
{
context: [
"/weatherforecast",
],
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
},
{
context :[
"/externalapi/*",
],
target : "http://localhost:8000",
secure: false,
changeOrigin: true,
}
]
module.exports = PROXY_CONFIG;
Step 3: Creation of the Services
export class ExampleServices{
_nodeUrl : any = '/externalapi/';
constructor( private httpClient: HttpClient){
}
mergeExamples(files:any) : Observable<any> {
console.log(this._nodeUrl);
return this.httpClient.get(this._nodeUrl+"get", files);
}
}
There are two from us ->
Why 504 Error occurs in this code ?Is it due to https-> http calling?
Is there any possibility to run the nodejs command from parent folder itself(currently the externalapi is inside the angular app, have its own node_modules)
Kindly help us with relevant answer and supporting documents.

Why I can't run VueJS with Express backend with hot reload?

I'm trying to use Express as a backend running a VueJS web application with hot reload, but I can't FETCH the content from the server.
vue.config.js:
module.exports = {
devServer: {
proxy: 'http://localhost:3000'
}
}
server.js:
const express = require('express');
const app = express();
const port = 3000
app.get('/hello', (req, res) => {
res.send({ "message": "Hello World" }) //Content
});
app.listen(port, () => {
console.log(`WebServer listening at port`);
});
That is running and /hello is working at port 3000.
Now, I'm starting both this way:
npm run server & nodemon server.js
Trying to fetch /hello in the Vue application, but it's not working. Am I missing anything?
<template>
<div class="flex-col">{{tasks}}
</div>
</template>
<script>
export default {
name:"ListToDo",
data(){
return{
tasks: []
}
},
methods:{
FETCH: function(){
fetch("/tasks/")
.then(res => res.json())
.then(data => this.tasks=data)
}
},
mount(){
this.FETCH()
}
}
The front-end is fetching /tasks, but the server does not have a route for /tasks, so it will respond with 404 Not Found.
One solution is to add a route for /tasks to your server's Express instance:
app.get('/tasks:myOptions(/*)?', (req, res) => {
res.send({ message: 'tasks', myOptions: req.params.myOptions })
})
Or you can update your component to use the /hello route already setup in the server:
export default {
methods: {
FETCH: function() {
fetch("/hello") 👈
.then(res => res.json())
.then(data => this.tasks=data)
}
}
}
}
If you prefer to keep your original /hello route while using /tasks from the client, the path will need to be rewritten client-side through the proxy, using the pathRewrite config shown below. However, this can't be done with the simple string proxy config, and specific route contexts (i.e., /tasks) must be specified:
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/tasks': {
target: 'http://localhost:3000',
pathRewrite: { '^/tasks' : '/hello' }
}
}
}
}

Why do I have 404 error (Angular 2 and Node js)

I have a form on my site and I want to send the data from fields to my email. I am using nodemailer and node js for this things. But when I submit form I have an 404 error on POST request.
form-component:
this.http.post('api/sendForm',{
to: environment.contactUsEmail,
from: 'zzz',
subject: 'zzz',
mailInfo: contactUsData,
}
).subscribe(() => {
this.cooperationFormGroup.reset();
});
server.ts: (path:backend/server.ts) folder backend is near folder src
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('api/sendForm', (req, res) => {
const payload = req.body;
const mailInfo = payload.mailInfo;
const transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
secure: 'true',
port: '465',
auth: {
user: 'email',
pass: 'pass',
}
});
const text = [...];
const mailOptions = {
from: 'zz',
to: payload.to,
subject: payload.subject,
text: text.join('\n'),
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
res.status(200).json({
message: 'successfully sent!'
})
}
});
});
app.listen(PORT, () => {
console.log(`Server is running in ${PORT}`);
});
I run server.ts in the folder backend using node server.ts and run angular app using npm start
As mentioned above in my comment: you need to pass the complete URL of your backend to post: use http://localhost:3000/api/sendForm instead of api/sendForm.
However, to manage different values during development and production, you might want to use environment.ts and environment.prod.ts:
environments/environment.ts:
export const environment = {
production: false,
urlToBackend: 'http://localhost:3000'
}
environments/environment.prod.ts:
export const environment = {
production: true,
urlToBackend: 'http://<IP>:3000'
}
service.ts:
While building the production build with npm run build, environment.ts will be replaced by environment.prod.ts as mentioned in the angular.json (see the object fileReplacements).
import { environment } from '../../environments/environment';
...
#Injectable()
export class AppService {
url = environment.urlToBackend;
constructor(private http: HttpClient) {
}
foo() {
return this.http.post(`${this.url}/api/sendForm`,{ ... });
}
}
My code is not accurate and you need to arrange it for your needs. However, I hope, you get the idea.
You need to mention the complete backend server URL in the first argument of the .post.
Change 'api/sendForm' to 'Your complete backend url'.
this.http.post( 'complete backend server url' ,
since you are running the node server on PORT 3000. Your backend URL will be http://localhost:3000/api/sendForm

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.

Getting browser-sync to play nice with ember-cli and a localhost API server

I've been trying to get browser-sync to play nice with ember-cli via ember-cli-browser-sync (installed via "ember-cli-browser-sync": "git://github.com/dylanharrington/ember-cli-browser-sync.git" in package.json as it isn't on the npm registery) with my localhost API server, but have been unable to get it to work.
Just doing
serverMiddleware: function(config) {
config.options.liveReload = false;
browserSync({
injectChanges: true,
reloadDelay: 10,
notify: false,
open: false,
proxy: "localhost:4200"
});
},
Works wonderfully for a local device, but fails at accessing my api at http://localhost:8000/api/1 from an external device (iPhone).
I tried to extend the proxy settings to include my local API via:
var url = require('url'),
proxy = require('proxy-middleware');
serverMiddleware: function(config) {
config.options.liveReload = false;
var proxyOptions = url.parse('http://localhost:8000/api/1');
browserSync({
injectChanges: true,
reloadDelay: 10,
notify: false,
open: false,
proxy: {
target: 'localhost:4200',
middleware: [proxy(proxyOptions)]
}
});
});
Which basically serves the API to my external URL provided by BrowserSync.
So I tried to utilise server:
serverMiddleware: function(config) {
config.options.liveReload = false;
var proxyOptions = url.parse('http://localhost:8000/api/1');
console.log(proxyOptions);
// proxyOptions.route = '/api';
browserSync({
injectChanges: true,
reloadDelay: 10,
notify: false,
open: false,
port: 3000,
server: {
baseDir: "./",
routes: {
"/app": "app",
"/assets": "dist/assets",
},
index: "app/index.html",
middleware: function (req, res, next) {
console.log(req.url);
next();
}
}
});
},
Which serves the correct index, and all the asset files, but causes an error with ember.
Does anyone have any experience doing this and which path I should try next? Is there a different NPM package I should try to use to proxy my API?
I gave up trying to solve this myself and ended up just using XIP, which might suit your needs.

Resources