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
Related
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.
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.
I have an function like this on my Express server, which is sending a file that depends on D3.JS.
app.get('/dashboard', function(req, res) {
var timestamp = utility.timestamp();
console.log('[' + timestamp + '] Request made to render dashboard.')
res.sendFile(__dirname + '/front_end/index.html')
});
This appears to be working correctly.
Once the file is served, it needs a data file in order to render properly. I attempt to access it as follows.
d3.tsv("../data/data.tsv", function(error, data) { // DO STUFF HERE }
Anyway, needless to say, because the file that is being sought is actually on the backend, I'm not able to access it this way from the code I have served the user.
I have also tried hitting an endpoint that sends the .tsv file. However, there is an error that has to do with cross domain requests.
d3.tsv("localhost:3000/userAccessData", function(error, data) { // DO SAME STUFF }
Does anyone know an effective way to send either both files using Express or access the file on the server using a request?
I initially fixed this problem by placing the resource file in a folder labeled as public. :D
Later, I found out that the browser actually caches the resource on the front-end and does not re-request it each time. To circumvent that and ensure up to date data is available, I added sockets.io to my project as well.
I'm trying to determine how to setup a web socket for the first time ever so a working minimal example with static variables (IP address for example instead of getservbyname) will help me understand what is flowing where.
I want to do this the right way so no frameworks or addons for both the client and the server. I want to use PHP's native web sockets as described here though without over-complicating things with in-depth classes...
http://www.php.net/manual/en/intro.sockets.php
I've already put together some basic JavaScript...
window.onload = function(e)
{
if ('WebSocket' in window)
{
var socket = new WebSocket('ws://'+path.split('http://')[1]+'mail/');
socket.onopen = function () {alert('Web Socket: connected.');}
socket.onmessage = function (event) {alert('Web Socket: '+event.data);}
}
}
It's the PHP part that I'm not really sure about. Presuming we have a blank PHP file...
If necessary how do I determine if my server's PHP install has this socket functionality already available?
Is the request essentially handled as a GET or POST request in
example?
Do I need to worry about the port numbers? e.g. if
($_SERVER['SERVER_PORT']=='8080')
How do I return a basic message on the initial connection?
How do I return a basic message say, five seconds later?
It's not that simple to create a simple example, I'm afraid.
First of all you need to check in php configuration if the server is configured for sockets with the setting enable-sockets
Then you need to implement (or find) a websocket server that at least follows the Hybi10 specification (https://datatracker.ietf.org/doc/html/draft-ietf-hybi-thewebsocketprotocol-10) of websockets. If you find the "magic number" 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 in the code for the header, you can be sure it does follow at least Hybi06 ...
Finally, you need to have access to an admin console on the server in order to execute the PHP websocket server using php -q server.php
EDIT: This is the one I've been using a year ago ... it might still work as expected with current browsers supporting Websockets: http://code.google.com/p/phpwebsocket/source/browse/trunk/+phpwebsocket/?r=5
I want to build an entire web app using only Javascript and MYSQL . How can I go about this if it's possible.
Try something like Jaxer, which will allow you to execute JavaScript on the Web Server and query databases.
Here are some syntax examples and usages:
Database, file, and socket access from JavaScript
alt text http://jaxer.org/images/Picture+4_0.png
Easily create RESTful JSON data services
alt text http://jaxer.org/images/Picture+6.png
Directly call server-side functions from the browser
alt text http://jaxer.org/images/Picture+2_0.png
You can do it with Jaxer. There are some screencasts that'll get you started. Also check out project Phobos. Jaxer integrates nicely in Aptana studio, Phobos in Netbeans.
If you can run javascript on the server, you can build a web-application with it (without the need for any other language like PHP etc.). Search the web for 'connection string mysql' to find out how to connect to your mySQL database and use ADO/ODBC. You'll need the MySQL ODBC-connector on the MySQL server.
Here's an example database connection (where MySQL server resides on the same server as the web server):
function connectDB()
{
var connectStr = "DRIVER={MySQL ODBC 3.51 Driver}; " +
"SERVER=localhost; " +
"PORT=[MySQL server port];" +
"DATABASE=[your database]; " +
"UID=[username];PWD=[password];" +
"OPTION=3",
conection = Server.CreateObject("ADODB.Connection");
//ERRID=>lib::connectDB::open
try {connection.Open(connectStr) }
catch(e) {errAlert(e,'rs::connectDB','connection failed',1) }
return connection;
}
(Where errAlert is a custom function to return the error)
You could write your application entirely in client side javascript with AJAX / REST calls to your database server - using something like CloudKit on your server (or CouchDB, which features a native JSON HTTP interface). On the client side, Dojo or YUI abstract out a great deal of the IO handling…
It's quite possible to write a web application using only javascript. One the key benefits of that is that since all code runs locally, you can make an application which doesn't require online connectivity.
The main detractor though, is that you can't hook it up to a database. But there are alternative data storage hacks you can use.
One example of such a javascript application is TiddlyWiki which is a personal wiki, contained in a single html file. The javascript application rewrites that html file, so you can carry it with you on a USB-drive or something.
You could look at triplify which should expose your database as json and rdf. I haven't actually used this but I would imagine that would let you bypass writing any server side js and talk to the database directly in a language javascript understands, using an ajax request and json.
You can build client-side applications in javascript, with an embedded database. HTML 5 has support for databases, and a couple of browsers have already implemented this part of the spec (safari, firefox with the gears plugin).
But this is only for clientside usage. You wont be able to share the database with other users. Also you can select which database you want to use. I think gears uses sqlite.
You will not be able to use Javascript and MYSQL without using something such as PHP on the server side to bridge the gap between the database and the Javascript on the client side.
Edit: I may be wrong, however I have no idea how you would run Javascript on the server side.