Post 200 OK page is not getting uploaded - javascript

I am running an application in express.
I have a
Button.which when pushed it wil send a Post to the server.
the 200 Ok, I am having the HTML page.
In Firebug, I can see the HTML payload in 200 OK.
But my page on the Broswer is not getting refreshed/uploaded.
Is it anything that should be done to have the url-refreshed (or) something like that .
I am using this :
res.sendfile('./temp.html');
The node snip is :
app.get('/', function(req, res){
res.sendfile('./temp1.html');
});
app.post('/next', function(req, res){
res.sendfile('./temp3.html');
});
I am trying to understand why when the 200 OK to post is having the data but it is not shown in the browser. it still have temp1.html

You want a redirect to be issued, not a 200 ok.
Using Express.js it would be this line of code
res.redirect('./temp3.html');
instead of
res.sendfile('./temp3.html)
For your other question, its trying to access the file that is located at this path: ./temp3.html , the ./ represents the current directory ../ is parent, which I assume is the one you're after.
As for your third question, if you dont want it to append to the url when redirecting I'm afraid that to my knowledge youre out of luck if you're using "normal post"-behavior.
I think its doable with ajax magic, however someone else has to correct me on that.
Read the Express res.redirect() docs here

Related

What's the difference between res.redirect and res.sendfile?

I completed a tutorial challenge of setting up a 'failure' page and a 'Try again' button. The button takes the user back to '/signup/html'. I used
app.post("/failure", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
But the tutorial used the res.redirect method.
The result is the same, but what's happening in the background, are there any differences using
res.redirect and res.sendFile?
Thanks,
On the face of it, redirect issues a redirect but sendFile sends a file.
I'm going to assume that code elsewhere responds to whatever path the tutorial said to use with redirect (let's say /signin) by sending that same file. So it might seem the same, but there are important differences:
Using redirect means you're only specifying that filename in one place, not two, which is better for maintenance.
If there's middleware set up on the other route (/signin or whatever), that middleware will get run with a redirect but not with your code.
redirect sends a message back to the browser telling it to request the other URL; your code sends the file directly.
With redirect, you can specify the redirect HTTP status code to use, for instance if you wanted to tell the client that the redirection is permanent (by specifying status code 302, though in your example that probably wouldn't be appropriate).

Use the same Node Script for Multiple Requests

I am using express js to build a small REST framework. in the app.js, I am forwarding to a separate script search.js, where I will send a json object (array) as the response to the requestor. for this, I am using the following code in the search.js.
router.get('/', function(req, res, next) {
//some search action
res.json(searchresult);
}
And my app.js looks like this.
app.use('/search',search)//use the search.js script
This works well for the first request. But when I reload the home page and resend a request, I get the following error.
Error: Can't set headers after they are sent.
So far, I've tried using res.write(JSON.stringify(search_result));. But this would not send the data correctly and I would get an error in the front end saying net::ERR_INCOMPLETE_CHUNKED_ENCODING.
What am I doing wrong? How can I make this work?

Express routing gives 404 for url's apart from localhost

My application currently serves fine making calls with Express, but I have a page now rendered by:
app.get('/user/:username', function(req, res){
serve html page (no problems)
}
and from that page, I'm making a request for
return $http.get('/api/user/:s').success(function (resp) {
stuff...
}
which is returning a 404 not found.
The call is in my Express app.js as
app.get('/api/user/:username', routes.api.getDBUser);
and I've been stumped on this problem for ages now. I feel like the issue is from something related to the URL.
EDIT:
app.use("/user", express.static(path.join(__dirname, 'static'))); //serving statics for localhost/user paths
app.get('/api/user', authentication.isAuthenticated, routes.api.getUser);
app.get('/api/users/:username', routes.api.getDBUser);
app.get('/api/user/friends', authentication.isAuthenticated, routes.api.getUserFriends);
app.get('/api/user/history', authentication.isAuthenticated, routes.api.getUserGameHistory);
is all the routes related to the user here. I'm not sure if this has something to do with it, but accessing a routing call when the url is something like localhost(port)/something, it's okay. The URL at this particular page I'm trying to make the call from is localhost(port)/user/something

Send a textbox value to another [duplicate]

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.

Communication between an express node server and its displaying html

Really fast, this question may have already been asked, but I am not totally clear on the terminology and have had no success when searching for a solution.
I am attempting to create a simple web application that can receive get and post requests. Then, I would like to take the information I receive from these requests and use them in a javascript file embedded in html that is displayed. I think it may be more clear with code. This is my app.js:
var express = require('express');
var app = express();
var assert = require('assert');
app.use(express.static('javascript'));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.listen(3000);
I would then like to be able to take information received from a get or post request, specifically in JSON format, and then be able to use it in javascript that I have linked to index.jade. To make matters slightly more confusing in index.jade the only line is:
include map.html
So ideally I would be able to get the information to javascript in that html file.
I want to be able to pretty continuously update map.html using javascript based on frequent get and post commands.
This could be a very simple solution, I am pretty new with web application programming in general, and I have been struggling with this problem. Thanks in advance, and ask if you need any clarification.
I think you need to understand what you are doing. You are creating a web server using node.js. Express framework simplifies that for you. The official documentation of express is pretty great. You should refer that especially this link.
Now, in your application, you need to create endpoints for GET and POST requests. You have already created one endpoint "/" (root location) that loads your home page which is the contents of the file index.jade. A small example is :
app.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
Jade is a templating engine which resolves to HTML. You should refer its documentation as well. Since as you said, you are not very familiar with these, you could simply use HTML as well.
After this tasks are quite simple. In your javascript, using ajax calls you can access the GET or POST endpoints of your server and do the desired actions.
Hope it helps!
The way I get it you want to be able to call an endpoint (lets assume /awesome) pass some info and then write to a Javascript file that you can then reference in your html.
Something like the below would write a main.js file in your public folder. You can make it write whatever you want.
var fs = require('fs');
fs.writeFile("/public/main.js", "console.log('Hello!')", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
You can then reference /public/main.js in your html.
Check that: Writing files in Node.js
If I misunderstood your intentions, apologies. :)
So you want to reviece continuously data from the server maybe web sockts are an option for you http://socket.io/docs/
This way u will open a stable connection from the client to the server. This is a great way if u want to get updates done by other clients.
If you want to trigger the changes by the client then ajaxs calls(http://www.w3schools.com/ajax/) as hkasera mentioned are the way to go.

Categories

Resources