I'm working through designing my first webapp, I've already written a significant portion of the frontend and now I want to make a very simple backend to begin implementing some of the functionality. I've spent the last few days learning as much as I can about effective backend development and other various things, but I've run into a huge problem. I fundamentally don't understand how to attach my front end and my backend (which I want to use nodejs for).
All I want is to use my browser to go to localhost:8080 and automatically see the html document with my frontend then within my frontend code have the app communicate with the server (to get json info or instruct the server to add things to a database or things like that).
Once you have installed node in your system.
Folder structure:
Keep your files in public folder inside app folder
Navigate to your application folder in Terminal or Command Prompt:
Then create a file as package.json and keep following code in it:
{
"name" : "YourAppName",
"version" : "0.0.1",
"description" : "App description",
"dependencies" : {
"mime" : "~1.2.7"
}
}
then come back to terminal and run npm install
Then create a file as server.js and keep following code in it:
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};
function send404(responce){
responce.writeHead(404,{"content-type":"text/plain"});
responce.write("Error 404: resourse not found");
responce.end()
}
function sendFile(responce,filePath,fileContents){
responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))});
responce.end(fileContents);
}
function serveStatic(responce,cache,abspath){
if(cache[abspath]){
sendFile(responce,abspath,cache[abspath]);
}else{
fs.exists(abspath,function(exists){
if(exists){
fs.readFile(abspath,function(err,data){
if(err){
send404(responce);
}else{
cache[abspath] = data;
sendFile(responce,abspath,data);
}
})
}else{
send404(responce)
}
})
}
}
var server = http.createServer(function(request,responce){
var filePath = false;
if(request.url == '/'){
filePath = 'public/index.html';
}else{
filePath = 'public'+request.url;
}
var abspath = './'+filePath;
serveStatic(responce,cache,abspath);
})
server.listen(8080,function(){
console.log("server running on 3000");
})
** This code is to help you get started with node js, for better understanding go to node documentation. Read about the mime module too, it is being used here.
You can use free cloud services such as Parse.com. this js sdk
You can use Grunt and using Connect plugin, create a simple server, sufficient for developing pure JS web applications.
Using Grunt basically requires 2 files
package.json
Gruntfile.js
package.json defines the dependencies required by Grunt to run. In your case it would include
grunt
grunt-contrib-connect (The plugin for setting up a server)`
It may also include additional dependencies based on your requirements.
Gruntfile.js defines the configuration for dependencies. In your case how the server should be setup. If you use plugins other that grunt-contrib-connect you should configure them too.
Reference:
Grunt: The JavaScript Task Runner
Related
I head to create Nuxt SPA with routing and mb API in future like that:
Backend server (on express or smth else) listen and on request give entire SPA to client.
Now user can use everything on client side (include routing) with no more else requests to backend (mb API requests only)
It means that server should give some .html file with js and css files as SPA and it will work on client side.
I tried to run some commands like nuxt build and nuxt generate
It looks like they return a same result - js files couldn't be found
And index.html file doesn't work properly
After some researching I found a solution
But now I got this:
It can't open the fourth js file in another js file. Path isn't right!
Every time I tried to run it as a static html file and from localhost (and also with using Live Server)
I think I did a lot of crutches and there should be another built-in function or feature that allows us to do what I want
I wrote a lot - if I made a mistake or you didn't get smth - please, ask! I need any help
To test your locally built application, you need to serve all files within the generated /dist folder. You can setup very easily a local web server using Express/Node.js as you already have Node.js installed when running Nuxt. Create a new folder and install express via npm (run npm install express).
Then, copy everything from /dist into /public and create a file server.js:
const express = require('express');
const app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000);
Run the web server with node server.js and you can access your generated files on http://localhost:3000.
i can hit the url like
localhost/foodbucket/app.js
and see everything.
I want to prevent this.
var config = require('./config/config.js');
var app = require('express')();
var http = require('http').Server(app);
var mysql = require('mysql');
var pool = require('./config/database.js')(config.MYPOOL,mysql);
var io = require('./lib/socket.js')(http,mysql,pool);
var notificationcron = require('./crons/notification.js')
(io,pool,mysql,config.NotificationStatus);
const router = app.Router();
router.get('/', "Error 404");
http.listen(4849, function() {
console.log('Listening on port ' + 4849);
});
Solution : Add an .htaccess file inside Node directory.
Write "Deny from all" in .htaccess
To avoid having your web server share the data on a URL: Don't put the file in a directory that your web server is configured to publish over HTTP in the first place.
Then, if you need to access that file from PHP (as your previous question says you want), use either a relative directory path (one which starts ../ to go up a directory) or an absolute path (like /var/secret_node_code/app.js) to access it.
Your app.js file in the server/www path.
I suggest create on the C:// a folder and paste you project to in after that, open a CMD and navigate to your folder and start your program with node app.js.
You should start your nodeJS application in console.
Just open a console (in windows run cmd, in linux start a terminal) and go to the path, where is your nodeJS application. Enter node app.js and press enter.
After that you can see the result in the browser in url "localhost"
I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.
I've an application with ES6/js/react UI and Spring boot server side. In my config.js I have host server URL and other properties that changes based on Env. I can use spring active profile to pick up diff set of properties. How do I do similar thing on the js part?
The application is deployed as spring boot application with embedded Tomcat.
Another way to put the question is How can I do Spring profile equivalent in NodeJs/JavaScript world?
My suggestion is to create a server using nodejs to host your static files and act as a proxy server to your backend.
Lately I've used this this seed for my react-projects. I like it a lot, it uses webpack for building the frontend and also provideds you with a handy proxy server that you can use during development (which also gets rid of any CORS issues).
Settings for proxy server: environments.js
I had exactly the need as you: how to use the same idea behind spring profile active environment variable. I used process.env:
const profile = process.env.NODEJS_PROFILES_ACTIVE;
I tested with Windows and Docker as an environment variable.
I have implemented the following and it seems to work .
Set up files like config-dev.js, config-QA.js, config-prod.js . These hold the configuration specific to each environment
Ex config-dev.js
const config_params = {dburl:"mongodb://localhost/mydb", port:5000};
module.exports = config_params
Set up file - config.js which has the below logic
let loadmodule = "./config-" + process.env.profile + ".js";
const setting = require(loadmodule);
module.exports = setting;
In the index file or server.js, import config.js
const config = require('./config.js');
Start the application as 'profile=dev node server.js'
I was wondering how to write files in Meteor to the server. I was looking at this NodeJS code, but it wasn't working when I tried it in the server javascript code.
var fs = require('fs');
fs.writeFile("/client/test", "Hey there!", function(err) {
if(err)
console.log(err);
else
console.log("The file was saved!");
});
It was saying that require wasn't defined. Anyways, does anybody know how to write files to the server in Meteor?
You need to use Npm.require instead of just require.
var fs = Npm.require('fs');
This will work for any module that is part of node or meteor (such as fs so its not a problem here). However, for other npm modules you would have to use Meteor NPM or write your own smart package