I am new to web development and cannot figure out how to send data from the Node server to the client while also serving an HTML page. I know that res.send() sends the data but I cannot use that without also changing the client display. Here is some code of what I'm trying to do (but does not work)
Server:
app.get('/home', function (req, res) {
res.send("String with info I want in HTML");
res.sendFile(__dirname + '/home.html');
});
Client:
<script>
var xhttp = new XMLHttpRequest();
alert(xhttp.responseText); //Using alert to check if I received the info I wanted
</script>
I know that res.send() sends the data but I cannot use that without also changing the client display.
You can. You just have to have the client ask for the data in the right way.
If the client side code is asking for a URL to be displayed as a new page then you will change the display. So don't do that. Use XMLHttpRequest.
var xhttp = new XMLHttpRequest();
alert(xhttp.responseText); //Using alert to check if I received the info I wanted
You need to:
Create the XHR object
Ask for a URL
Send the request
Wait for the response
Look at the response
You've skipped over steps 2, 3 and 4!
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/home");
xhttp.addEventListener("load", function () { alert(this.responseText); });
xhttp.send();
res.render() function does the job!
res.render("your html page" , { variable : "String with info you want to send." })
Related
I am building a web application using the Express framework. I'm trying to send the username of an account (which is stored in a cookie) to the backend. This is the code in the frontend JS that sends the HTTP Post request:
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/loggedInAutoSubmitForm', true);
httpRequest.setRequestHeader("Content-type","application/application/json");
httpRequest.send(JSON.stringify(content));
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var json = httpRequest.responseText;
console.log(json);
}
else {
console.log("some error happened");
}
};
content is defined and this is what I get in Chrome's console when I log content:
{"username":"testUser1"}
The content of this request is correct, but I'm not receiving it with the router in index.js. This is the backend code:
var express = require('express');
const router = express.Router();
router.post('/loggedInAutoSubmitForm', function(req, res) {
console.log(req.body);
// find user and render logged in page
});
I haven't implemented the code yet, but the problem is that I'm getting an empty request body. This is what happens in my console when I log req.body:
{}
Also, I get nothing logged in Chrome's console after the request has been sent, so I'm thinking maybe the request didn't end?
I'm fairly new to web development and I'm not sure if this is the correct way to send a Post request from the frontend. If it is, I have no idea what is wrong with this code. I have searched online but it seems that this is the proper way to receive the Post request using router. Is there any way to make it work? Any help is appreciated.
I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
So I have a webapp that is built on the nodejs framework. At the moment I am using an NGINX Reverse Proxy that uses OIDC for authentication. Once the user is authenticated it then forwards them on to the nodejs backend.
I want to grab the users email address from the header which is passed from the reverse proxy to the backend and print it on my homepage so it will say Welcome XXX
Now I can see that if i add the below in my app.js it will print the headers to the command line so i know it is being passed, but i just do not what javascript i need to achieve this
app.get('/home', function (req) {
console.log(req.headers);
});
The example found here Accessing the web page's HTTP Headers in JavaScript does present me with a popup but it does not grab show the info i need which is 'x-user': 'fffffff#ffff.fff'
I tried this code also but it is not picking it up for me
<script>
function getClientIP(req){
return req.headers['x-user'];
}
</script>
<h3><b><script>getClientIP();</script></b></h3>
I have this printing to the console.log so i know for a fact x-user is present in the request.
Figured it out
<script>
function parseHttpHeaders(httpHeaders) {
return httpHeaders.split("\n")
.map(x=>x.split(/: */,2))
.filter(x=>x[0])
.reduce((ac, x)=>{ac[x[0]] = x[1];return ac;}, {});
}
var req = new XMLHttpRequest();
req.open('HEAD', document.location, false);
req.send(null);
var headers = parseHttpHeaders(req.getAllResponseHeaders());
</script>
<script>
function here() {
document.write(JSON.stringify(headers["x-user"]));
}
</script>
<h3><b><script>here();</script></b></h3>
I'm writing a web app in express and one of the resources is exposed through an API with an endpoint on 'api/tone'. The API is just a wrapper for one of Watson's services, but I don't call them directly so as not to do all the authentication and payload building on the front-end. The API itself is working just fine because when I try to reach it with POSTMAN, it responds correctly.
POSTMAN request info:
POST: localhost:3000/api/tone
Headers: "content-type": "application/x-www-form-urlencoded"
Body: "text": "The king is a lovely chap. He makes me feel like I'm back at home with my family."
Postman request
This request works exactly as intended.
The app is just a prototype showcasing other functionalities, so it doesn't use any sort of authentication.
The Javascript Request
The problem comes when I try to call the API from my front-end.
function sendRequest(text) {
var payloadToWatson = {};
payloadToWatson.text = text;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("POST", messageEndpoint, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(JSON.stringify(payloadToWatson));
}
Here I get a POST bad request error. When I log the error on the backend, this comes off:
{"code":400,"sub_code":"C00007","error":"No text given","x-global-transaction-id":"ffea405d5a5a00dd017a0dbb"}
I'm 99% sure the problem is in the front-end API caller, otherwise, POSTMAN requests wouldn't work, but I still can't find how to get it working.
The problem is that you are not sending the same thing. With postman you are not sending json.
Just send text without stringifying :
xhttp.send({text: text});
OK, I finally made it work. And by I, I mean is used POSTMAN code tool. Instead of sending the data to be analyzed as a JS object or a stringified JSON:
var payloadToWatson = {};
payloadToWatson.text = text;
...
xhttp.send(JSON.stringify(payloadToWatson));
I had to do was create a string using equal signs between the parameters and the values:
var data = "text=" + text;
xhttp.send(data);
Works perfectly now.
It is common to use HTTP method POST to send a form.
For example, if the form action is "/login",
the request would send to server, and the URL would be like "index/login".
However, I want to implement two things.
Use HTTP method POST without "form". I want to send my own message.
And without changing the URL after the AJAX
Thanks.
Update: reply to DvS
The studies I have researched use libraries like jQuery or AngularJS.
But I want to implement by pure javascript.(like XMLHTTPRequest)
And I don't know how to use "NOT A FORM" in AJAX.
Maybe there's some references I can study?
Thanks again.
Try jQuery's AJAX call
http://api.jquery.com/jquery.ajax/
$("#id_of_button_to_submit").click(function(){
$.ajax({url: "/login", success: function(result){
//do things with your result
$("#div1").html(result);
}});
});
I found answer in "You might need jQuery"
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var resp = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
The server side is implemented by Node.js and express
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.post('/newindex', function(req, res){
console.log("req received!");
res.send('This is POST METHOD');
})
app.listen(8888);
Old post but I ran into this problem and it got to my search results, and I suspect that the cause is the same.
Basically don't use a form action and submit button.
Then call the function using a regular button, or whatever else you want.
Seems like default form behavior for the submit button but without an action is HTTP GET to the current page, which runs and of course mucks everything up.