Skip to content

Instantly share code, notes, and snippets.

@honwhy
Created May 26, 2016 14:31
Show Gist options
  • Select an option

  • Save honwhy/39aff538c1c5019198737d6ac198b46e to your computer and use it in GitHub Desktop.

Select an option

Save honwhy/39aff538c1c5019198737d6ac198b46e to your computer and use it in GitHub Desktop.
ajax 302 code
var http = require('http');
http.createServer(function(req, res) {
if(req.url == '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(makeHtml());
} else if(req.url == '/ajax302'){
res.writeHead(302, {
'Content-Type': 'text/html',
//'Location': 'http://localhost:9000/forward' // alert 200
'Location': 'https://github.com/join' // alert 0
});
res.end();
} else if(req.url == "/forward") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('session is invalid');
}
}).listen(9000);
console.log('Server running at http://localhost:9000/');
function makeHtml() {
var htmlArray = [];
htmlArray.push("<!DOCTYPE html>");
htmlArray.push("<html lang='en'>");
htmlArray.push("<head>");
htmlArray.push("</head>");
htmlArray.push("<body>");
htmlArray.push("<h1>Ajax 302 Test</h1>");
//htmlArray.push("<form method='post' action='/ajax302'>");
//htmlArray.push("<button type='submit'>submit</button>");
//htmlArray.push("</form>");
htmlArray.push("<button onclick='send()' type='button'>Send</button>");
htmlArray.push(makeXMLHttpRequestContent());
htmlArray.push("</body></html>");
return htmlArray.join("\n");
}
function makeXMLHttpRequestContent() {
var jsArray = [];
jsArray.push("<script>");
jsArray.push("function send() {");
jsArray.push(" var xhr = new XMLHttpRequest();");
jsArray.push(" xhr.onreadystatechange = function() {");
jsArray.push(" if(xhr.readyState == 4) { ");
jsArray.push(" alert(xhr.status);");
jsArray.push(" }");
jsArray.push(" };");
jsArray.push(" xhr.open('POST', '/ajax302');");
jsArray.push(" xhr.send(null);");
jsArray.push("}");
jsArray.push("</script>");
return jsArray.join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment