I am trying to understand why an ajax response would be sent when outside of a function, but not within the function. The response object is accessible within the function, but it will not send the actual response. What would cause this type of behaviour?
app.post('/login', urlencodedParser, function(req, res){
if (!req.body) return res.sendStatus(400);
var password = JSON.stringify(req.body.password);
var username = JSON.stringify(req.body.username);
//res.send('Invalid'); //This sends a response
login.login(username, password,function(err,content) {
if(err){res.send('Invalid');} //This does not send a response
else {
agent_valid = content[0].valid;
if (agent_valid === 0)
{
console.log(agent_valid); //agent_valid is appearing as 1 or 0
console.log(res); //res exists and is written to console
res.send('Invalid'); //This does not send a response
}
if (agent_valid === 1)
{
res.send('Valid'); //This does not send a response
}
}
});
});
This is the javascript sending the post request:
ajaxRequest.send(JSON.stringify({username:username, password:password}));
ajaxRequest.onreadystatechange = function() {
if(this.readyState == 4 && this.responseText == 'Invalid') {
window.alert(this.responseText)
};
if(this.readyState == 4 && this.responseText !='Invalid'){
window.alert(this.responseText)
};
}
Related
I'm sending HTTP requests and receiving responses with the following code:
var xhr = new XMLHttpRequest()
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if (userInfo.type == 2) {
userType = 'professor'
}
xhr.onreadystatechange = function() {
try {
if (this.status == 200 && waiting) {
waiting = false;
var courses
try {
courses = JSON.parse(xhr.response)
} catch (jerr) {
courses = []
}
sup.courseArray = courses;
console.log(sup.courseArray)
sup.render()
}
} catch (err) {}
}
xhr.open('GET', 'http://localhost:8080/course/read/' + userType + 'Id/' + userId)
xhr.send()
As you can see, I'm only accessing response in the callback, so the server has responded and xhr has been initialized at that point. If I simply call console.log(xhr), I can clearly see response is a non-empty string:
response: "[{\"id\":1,\"professorId\":1,\"name\":\"java\",\"code\":\"CS1017\"}]"
However, if I call console.log(xhr.response), I get
<empty string>
Does anyone know why I'm seeing this discrepancy?
this.status == 200 will be true as soon as xhr.readyState == 2, but the request will not be completely fulfilled until xhr.readyState == 4; at readyState == 2 response will still be empty.
console.log(xhr) will eventually show the status at readyState == 4, but that's 2 readyStates later than when your code tries to access xhr.response.
You have to check that both status == 200 and readyState == 4 are true to be sure a complete response has arrived.
why not try using using JS native fetch instead
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if(userInfo.type == 2) {
userType = 'professor'
}
fetch('http://localhost:8080/course/read/' + userType + 'Id/' + userId)
.then(r => r.json())
.then((response) => {
waiting = false;
sup.courseArray = response;
console.log(sup.courseArray);
sup.render();
})
.catch((e) => {
waiting = false;
console.log(e);
});
I am building a cart which sends the order from Js to my razor page but when i fires it, it seems to fail, even after inputing the right url path
This is my Cart.js script
function updateOrder(order) {
var r = new XMLHttpRequest();
r.open('post', '/Cart?handler=LogOrder');
r.setRequestHeader('Content-Type', 'application/json');
r.send(order);
r.onload = function () {
let res = r.responseText;
if (r.readyState == 4 && r.status == 200) {
alert('Your order was processed successful and will be delivered to you shortly!!!');
window.location = '/shop'; // redirect
}
else {
alert('Oops.. An error occured seems like we were unable to process your order');
}
}
}
My OnPost Razor pages CartPageModel
public async Task<IActionResult> OnPostLogOrder(Order order)
{
if (order != null)
{
await orderRepo.AddOrder(order);
}
return RedirectToPage("Shop");
}
When ever i try to save it fails
I'm using slim cropper to upload avatar's on my codeigniter project , It works perfectly on my localhost but on the server , the ajax call to the php that does the image upload keeps giving a 403 forbidden error, below is the section of the code:
function send(url, data, progress, success, err) {
var xhr = new XMLHttpRequest();
if (progress) {
xhr.upload.addEventListener('progress', function (e) {
progress(e.loaded, e.total);
});
}
xhr.open('POST', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var text = xhr.responseText;
// if no data returned from server assume success
if (!text.length) {
success();
return;
}
// catch possible PHP content length problem
if (text.indexOf('Content-Length') !== -1) {
err('file-too-big');
return;
}
// if data returned it should be in suggested JSON format
var obj = null;
try {
obj = JSON.parse(xhr.responseText);
} catch (e) {}
success(obj || text);
} else if (xhr.readyState === 4) {
err('fail');
}
};
xhr.send(data);
}
From what I've read , providing a CSRF token might solve the problem, but the request is made from the same domain and I don't require that on my localhost. What could be the problem?
I'm quite new to node.js and web development in general (so if I'm entirely off base and you have good material for me to consume I'd really like to see it).
I'm trying to prototype passing a JSON object back and forth between node.js server and http client. The client side so far looks like:
<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);
function passArg() {
console.log("I'm here")
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//var json = JSON.parse(xmlhttp.responseText);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
}
var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xmlhttp.send(data);
get_json();
}
function get_json(){
console.log("getting json");
var xmh = new XMLHttpRequest();
xmh.open("GET", "/playlist/playlist.json", true);
xmh.send();
xmh.onreadystatechange = function() {
if (this.readyState == this.DONE ) {
if (this.status == 200) {
var json = JSON.parse( this.responseText );
console.log(json.email + " "+ json.password + " " + json.access_date);
}
else if (xmh.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
}
}
</script>
And the server side is coded as
app.post("/", function (req, res) {
console.log('Request received');
req.on('data', function (chunk) {
console.log('GOT DATA!');
json = JSON.parse(chunk);
json.access_date = "12.04.17";
write_json(json)
console.log("finished writing- in app_post")
});
console.log("passing all clear to client")
res.writeHead(200);
res.send();
})
function write_json(chunk){
console.log("WHADDUP")
console.log(JSON.stringify(chunk))
fs = require("fs")
var filename = "./public/playlist/playlist.json";
var file = require(filename);
file = chunk;
fs.writeFile(filename, JSON.stringify(file), function(err){
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
}
)
console.log("finished writing - in write_json")
}
On the serverside console the following output is generated
Request received
passing all clear to client
GOT DATA!
WHADDUP
{"email":"hey#mail.com","password":"101010","access_date":"12.04.17"}
module.js:428
throw err;
^
SyntaxError: public/playlist/playlist.json: Unexpected end of input
And on the client side of things the console reads
(index):15 I'm here
(index):41 getting json
(index):45 GET http://localhost:8080/playlist/playlist.json net::ERR_CONNECTION_RESET
From this I read that the asynchronous POST event is sending the all clear to call get_json before the file itself is updated. And it seems the updating of the file on the server side isn't working as well. How do I structure the calls to make the edit quite smooth?
The quick answer is to create a function to call res.send, pass it to your write_json function, and invoke it from inside your writeFile callback.
app.post("/", function (req, res) {
console.log('Request received');
req.on('data', function (chunk) {
...
write_json(json, function() {
console.log("passing all clear to client")
res.writeHead(200);
res.send();
console.log("finished writing")
});
});
});
function write_json(chunk, onFinishedWriting){
...
fs.writeFile(filename, JSON.stringify(file), function(err){
if (err) {
return console.log(err);
}
else {
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
onFinishedWriting();
}
});
}
However when you find yourself writing code like this:
});
});
});
then you are probably in the proverbial "callback hell". I suspect that what you want is to use promises. Here's a question specifically about promises and writeFile that will probably help you.
I am testing ways to use a PhantomJS server with Python's Requests library.
The GET and POST requests work as expected and I can get the PhantomJS server to request any page I want and put the results to the console, but I can not figure out how to send the page content back using response.write(page.content). The request object has no text, content or usable raw content. The only way to get response.write() to work as expected is to hardcode the response content. If I add keep-alive to true the request functions hangs.
Here is my server.js
var webserver = require('webserver').create();
page = require('webpage').create();
var service = webserver.listen(8080, function(request, response) {
if (request.method == 'POST') {
console.log(request.post);
var content = '';
page.open(request.post, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
response.statusCode = 200;
response.write('Page not responding.');
} else {
content = page.content;
response.statusCode = 200;
response.write(content);
}
})
} else {
response.statusCode = 200;
console.log(request.method == 'GET' );
response.write('No URL provided');
}
response.closeGracefully();
});
The Python code is straightforward:
import requests
response = requests.post('http://127.0.0.1:8080, data='http://python.org')
The connection needs to be closed after sending data back: response.close();
Also I'd suggest using a variable in POST request, cause response.post is actually an object.
var webserver = require('webserver').create();
page = require('webpage').create();
var service = webserver.listen(8080, function(request, response) {
if (request.method == 'POST') {
var url = request.post.url;
console.log(url);
var content = '';
page.open(url, function (status) {
if (status !== 'success') {
console.log('FAIL to load the address');
response.statusCode = 200;
response.write('Page not responding.');
response.close();
} else {
content = page.content;
response.statusCode = 200;
response.write(content);
response.close();
}
})
} else {
response.statusCode = 200;
console.log(request.method == 'GET' );
response.write('No URL provided');
respone.close();
}
});
Then POST with url variable:
import requests
response = requests.post('http://127.0.0.1:8080, data = {'url':'http://python.org'})