how to set value of text field in html from nodejs? - javascript

I'm doing project in nodejs and html .can anybody help how to set value to text field in html from server.js. For example I've text field with id 'name' on index.html. i use res.body.name = 'nametest' .but its not working .please give me a simple example . Thank you friends

In order to set a field from the server, you want to make it a preset value which you define when sending the HTML or you want to set it dynamically later on. The first option is easy, the second one a bit advanced.
Let's look at option 1. This is just a very basic example! Please don't use this in production.
index.html
<!DOCTYPE html>
<html>
<head><!-- your stuff here --></head>
<body><input type="text" name="someVal" value="{{someVal}}"></body>
</html>
This might be your HTML. Just but a distinctive placeholder where you want your value to go. There might be better techniques out there to do this, but for the sake of simplicity I chose this way.
server.js
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500);
res.end(err);
return;
}
data = data.toString().replace(/\{\{someVal\}\}/, 'your value here');
res.writeHead(200);
res.end(data, 'utf8');
});
}).listen(8080);
This server.js will open a HTTP server on port 8080. It will try to read index.html from the same directory. If it fails, it will send the error message to the client, else it will replace your placeholder in your HTML with your value and then send the modified content to the client.
If that's all you want to do, PHP might do a better job for you (but that's just my 2 cents :) )
Option 2 is a lot more elaborate. You would have to either use AJAJ (Asynchronous Javascript and JSON) which requires the client to know when to fetch the value or you could make use of websockets which enable the server to push a value to the client. For either of those there are a lot of tutorials out there which are a lot more detailed than anything I could put together for you here.
If you want to use those techniques, but are a bit unsure about their iomplementation, you might want to look at frameworks like Meteor and Socket.IO

You can't set a client-side thing from the server-side. They're absolutely different physical layers.
What you need is AJAX to request a resource from your Web app to your NodeJS server-side app, and set what you put in you response to the whole text field.
Maybe you'll need to take a look at ExpressJS to build a simple RESTful service to share resources between your client and server tiers.

Related

Upload JSON File to my server with vue and node js

I'm new to node js and vue development and I want to create a process where I can create and upload a JSON file to my server when the user saves data in a form. This process should be done in the background. Later I want to read and update that file from the server when the user changed something.
So my first idea was to use fs.writeFile() this doesn't work very well and I think this only works for local stuff is that correct?
var fs = require('fs')
export default {
methods:{
send(){
fs.writeFile("/test.json","Hello World!",function(err){
if(err){
throw err;
}
});
}
}
}
Furthermore it looks like fs.writeFile doens't work with vue because it throws this error:
TypeError: fs.writeFile is not a function at VueComponent
So my second idea was to use express js with the app.post('/api/apps',...) and app.get() method. Here I have no idea how to implement that into the vue framework because I have to call the api like mydomain.com/api/apps but this doesn't work too.
So what is the best way to create, read, upload, delte files into a specific folder on my server? And how it works with vue? I tend to express js.
I'm using vue cli :)
Thanks in advance :)
EDIT
Now what I do is:
I created a new folder in my vue project root and named it "backend". In this folder I created a file named index.js and put this code
app.post('/appjson',(req,res) => {
fs.writeFile("/appjson/myJson.json",req.body,function(err){
//handle error
});
});
on the client side I put this code
axios.post('myDomain.com/appjson', {
JSONdata: myJSONdata,
})
My project looks like:
So when I build I get the dist folder and this I can upload on my server and it works fine. But I can't do the call to my backend? Whats wrong do I call the wrong link? Or how can I access my backend? Is the project struture correct or do I need to add the backend to a specific folder?
Vue is client side, your code is trying to write something to the filesystem of the user thats using your website. what you want to do is send this data to your NodeJS server, this requires using a package like Axios to send data to and from the server without refreshing the page. Axios is pretty straight forward to use, what you need will look similar to the function below.
saveJSON (myJSONData) {
const url = myNodeJSURL/savescene
return axios.post(url, {
JSONdata: myJSONdata,
})
Read some tutorials on ExpressJS, It's a pretty painless framework to use. You'll get the data stored in the body of the HTTP request and then you can use fs.writeFile to save data to the local filesystem of your server. Let me know if you need more help.
EDIT:
Your front end needs to be access a domain or IP address associated with your back end in order to communicate with it. Add the snippet below to your ExpressJS application and then when you run the server any requests to localhost:3000 will be handled by your app. You'll also have to update the URL in your Axios call.
app.listen(3000, function () {
console.log('my server is listening on port 3000!')
})
this setup only works for testing purposes because client and server will have to be on the same machine for localhost to mean the same to both. If you want this project to be public then you need to get your own domain for your site and host the ExpressJS application through there. Google compute makes this pretty easy to do, I'd look into that if I were you.

Multipage Node.js Server Without Routing Bloat?

Can I set up a multipage Node.js web server that does not require a unique route for every page?
I have a simple HTTP server set up using Node and Express, using EJS for view engine. My routing currently looks like this:
// routing
app.get('/', routes.index);
app.get('/hig', routes.hig);
app.get('/proto', routes.proto);
app.get('/design', routes.design);
app.get('/process', routes.process);
app.get('/demo', routes.demo);
app.get('/api', api.index);
app.get('/api/rules', api.list);
app.get('/api/rules/:id', api.ruleid);
I'd like to be able to easily update my site to have pages such as /hig/section1 and /hig/section2 (and so on) without having to update the route table each time and restart the server. More importantly, I'd like to be able to quickly and easily make multiple versions of a demo and be able to link to them.
For example, create a new demo and link a user to /demo/version23 while linking someone else to /demo/version 35, allowing me to illustrate different functionality without breaking previous demo sites. It would not be long until /demo/version108 and beyond exist, so having a sane way to create these without having 108+ routes is preferable.
The only method I've been successful at so far is updating route tables. Is there another way I can point to different pages in the route table that will allow me to more easily add new pages?
You should consider making part of url variable for ex as /hig/:section.
You should then get section as a parameter which you can use to map to different content, page or do any other logic that you want with that.
In my express api, I have a wildcard get. The endpoint var parses the keyword and then whatever you decided to do with that is up to you. In mine I have some if statements to change the database model etc but you don't need that... I would suggest keeping the 404 send, so if somebody hits an undesired url you can just give them whatever status code.
app.get('/:endpoint', function (req, res) {
var endpoint = req.params.endpoint;
if( endpoint == 'something' ){
} else if( endpoint == 'something' ){
} else { return res.send(404, { erorr: "That resource doesn't exist" }); }
// Display the results
});
I implemented simple demo project to achieve multi-app structure.
https://github.com/hitokun-s/node-express-multiapp-demo
With this structure, you can easily set up and maintain each app independently.
I hope this would be a help for you.

Express.js: reverse proxying different web app along with assets

I want to allow an authenticated client in Express to access to other web applications that are running on the server, but on different ports.
For example, I have express running on http://myDomain and I have another application running on say port 9000. I want to be able to reach the other app through http://myDomain/proxy/9000.
I had a little bit of success using node-http-proxy, for example:
function(req, res) {
var stripped = req.url.split('/proxy')[1];
var path = stripped.split('/');
var port = path.shift();
var url = path.join('/');
req.url = url;
proxy.web(req, res, {
target: 'http://127.0.0.1:' + port
});
}
However, the big problem is that when the web app makes GET requests, such as for /js/lib.js, it resolves to http://myDomain/js/lib.js, which is problematic because express is not aware of those assets. The correct request would be to http://myDomain/proxy/9000/js/lib.js. How do I route all these additional requests?
What you need to do is to replace URLs in the initial page with the new URL pattern. What is happening is that the initial page that your reverse proxy returns has a reference to:
/js/lib.js or http://myDomain/js/lib.js
so when the browser makes a second request it has the wrong pattern for your reverse proxy.
Based on the incoming request you know what the pattern should look like. In your example it's http://myDomain/proxy/9000. You then fetch the appropriate page from the other server running on http://127.0.0.1:9000/. You do a string replace on any resources in that file. You'll need to experiment with the pattern but you might look for 'script src="/' or 'href="/' and you might find regex helps with the pattern if, for example, the src attribute isn't the first listed in a script tag.
For example you might find 'scr="/' and then you replace it with 'src="/proxy/9000/' that way when the browser asks for that local resource it will come through with the port that you're looking for. This is going to need experimentation and it's a great algorithm to write unit testing around to get perfect.
Once you've done the replacement you just stream that page to the client. res.send() will do this for you.
Something else that you might find useful is that ExpressJS gives you a way to pull out the port number with a little less hassle than you're doing. Take a look at this example:
app.get('/proxy/:port', function(req, res){
console.log('port is ' + req.params.port);
});
I don't think http://myDomain/proxy/9000 is the correct way to do it. Web pages are going to assume the site's domain to be just myDomain and not myDomain/proxy/9000, because that is what the standard says.
Your use case would be better served by using subdomains like 9000.proxy.myDomain.

How to read and write JSON offline on local machine?

Problem
I need a way to store and collect JSON data in an entirely offline(!) web application, hosted on a local (shared) machine. Several people will access the app but it will never actually be online.
I'd like the app to:
Read and write JSON data continuously and programmatically (i.e. not using a file-upload type schema)
Preferably not require any software installation other than the browser, specifically I'd like not to use local server. (edit: I may be willing to learn a bit of Python if that helps)
The amount of data I need to store is small so it is very much overkill to use some sort of database.
Solution?
My first thought was to let the html5 file API, just read/parse and write my JSON object to a local txt file, but this appears not to be possible?!
Local storage is not applicable here right, when several people - each with their own browser - need to access the html?
Any ideas?
note
I know this topic is not entirely novel, but I think my situation may be slightly different than in other threads. And I've spent the better part of the last couple hours googling this and I'm none the wiser..
Have you considered Python's Json module? http://docs.python.org/2/library/json.html
Using this you can convert python objects to and from json strings. You can store the strings however you want to
You can't use Localstorage to enable such features because every client will have its own dataset stored.
Have you ever considered using a java applet to handle such informations ?
You could start a java applet using it as a bridge between browser clients and as a store of informations.
Browsers could share such information using websockets.
Some times ago I build demo with such solution.
Check it at: https://github.com/KingRial/SBrower
In this demo I open a browser/tab which starts a java Applet to create a websocket server.
All the browsers/tabs are just clients connecting to the websocket server and sharing informations.
Since python is one of the question tags, I am giving a python solution:
import json
#reading
file_json = open("json.txt")
print file_json
python_json_object = json.loads(file_json)
print python_json_object
file_json.close()
#writing
file_json = open("json.txt", 'w')
file_json.write(json.dumps(python_json_object))
My suggestion would be something like WampServer (Windows, Apache, MySQL, PHP). I've seen a few tutorials about adding Python to that mix.
You would have access to reading and writing JSON data to the local storage or placing your data in a local database.
I know you said you don't want to opt for local server, but nodejs could be the solution. If you know JavaScript, then it's very simple to set one server up and let everybody access to the server from any browser. Since it's entirely JavaScript you don't even have conversion issues with the JSON format.
For storing the JSON you can use the FileSystem built-in library of nodejs which lets you read and write from a file, so you don't even need a database.
This is using Node.js and Express.
const express = require('express');
const http = require("http");
const app = express();
const server = http.createServer(app);
const fs = require('fs');
const newestData = {
"id":123,
"title":"spoon"
}
app.get("/",async(req,res,next)=> {
res.status(200).send('Hello World!');
fs.readFile("Metadata.json", 'utf8', (err,content)=>{
if(err) throw err
let data = JSON.parse(content)
data.push(newestData)
fs.writeFile("Metadata.json",JSON.stringify(data), (err)=>{
if(err) throw err
})
})
})
const port = process.env.PORT || 5000;
require("dotenv").config();
server.listen(port, function() {
console.log('Express server listening on port ' + port);
});

Sending javascript files using Node server with NowJS

This question should be simple to answer for anyone with Node experience -- unfortunately I am an extreme novice.
I am writing a web application for a board game that will use a server-client architecture to show real-time changes made to the board to all clients. The application uses Raphael to display the graphics.
I have created a server that successfully sends the HTML file to respond to any request, but the board does not display -- only the raw HTML without any Javascript comes up. I think it is because I have programmed the server to always respond with the HTML file, and I can't figure out how to send the Javascript files (client.js, raphael.js) to the client so that the page can load properly.
The relevant code is below. For now, I'm just trying to get the browser to draw one Raphael element so I can see that the client is properly getting the Javascript files it needs to load the page.
On the server side:
var fs = require('fs');
var server = require('http').createServer(function(req, response){
fs.readFile('index.html', function(err, data) {
response.writeHead(200, {'Content-Type':'text/html'});
response.write(data);
response.end();
});
});
On the client side:
$(document).ready(function(){
var R = Raphael("container", 1000, 700);
this.R.path("M0,0l1000,700").attr({"stroke-width": "5"});
});
You can assume that the HTML file is formatted correctly and includes references to all the JS files -- I've had the application working great without the server-client architecture for a while now. Also, I am using NowJS, so any solution that incorporates that framework would be welcome as well.
Thanks for any help!
on your server side you are always returning index.html
check out how the createServer method is used in this gist: https://gist.github.com/1245922
it evaluates the extension to return a proper mime-type and then calls the stream file function to return the requested url/file from the fs.
if you're going to use this with nowjs then you'll want to also use along the lines of:
var everyone = nowjs.initialize(server);
Use the static middleware
http://senchalabs.github.com/connect/middleware-static.html

Categories