所以我正在尝试创建一个非常基本的node.js服务器,它接受一个字符串请求,从一个数组中随机选择一个并返回所选字符串。不幸的是,我遇到了一些问题。
这是前端:
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","server.js", true);
xmlhttp.send();
string=xmlhttp.responseText;
}
这应该将请求发送到server.js:
var http = require('http');
var choices=["hello world", "goodbye world"];
console.log("server initialized");
http.createServer(function(request, response)
{
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.on(string);
console.log("string sent");
}).listen(8001);
很明显,这里出现了一些问题:
我感觉我“连接”这两个文件的方式在xmlhttp.open
方法和使用response.on
将字符串发送回前端都不正确
我对如何在localhost上调用此页面感到困惑。前端名为index.html,服务器发布到8001.在初始化server.js后,我应该在localhost上访问初始html页面的地址是什么?我应该将其更改为.listen(index.html)
或类似的内容吗?
我是如何实现这一点(使用.responsetext
等)还有其他明显的问题。)
(对于很长的多问题帖子感到抱歉,但各种教程和node.js源都假设用户已经了解这些内容。)
答案 0 :(得分:60)
您的请求应该是服务器,而不是实例化它的server.js文件。因此,请求应如下所示:xmlhttp.open("GET","http://localhost:8001/", true);
此外,您正在尝试提供前端(index.html)并在同一URI上提供AJAX请求。要实现这一点,您将不得不向您的server.js引入逻辑,以区分您的AJAX请求和普通的http访问请求。为此,您需要引入GET / POST数据(即调用http://localhost:8001/?getstring=true
)或为您的AJAX请求使用不同的路径(即调用http://localhost:8001/getstring
)。然后,在服务器端,您需要检查请求对象以确定在响应上写入的内容。对于后一种选择,您需要使用'url'模块来解析请求。
您正在正确调用listen()
但错误地编写了回复。首先,如果您希望在导航到http://localhost:8001/时提供index.html,则需要使用response.write()
或response.end()
将文件内容写入回复。首先,您需要包含fs=require('fs')
才能访问文件系统。然后,您需要实际提供文件。
如果您异步使用XMLHttpRequest,则需要指定一个回调函数(第三个参数= true,就像您所做的那样)并希望对响应执行某些操作。现在的方式,string
将是undefined
(或者null
),因为该行将在AJAX请求完成之前执行(即responseText仍为空)。如果您同步使用它(第三个参数= false),您可以像完成一样编写内联代码。建议不要这样做,因为它会在请求期间锁定浏览器。异步操作通常与onreadystatechange函数一起使用,该函数可以在完成后处理响应。您需要学习XMLHttpRequest的基础知识。开始 here 。
这是一个包含以上所有内容的简单实现:
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend(index.html的一部分):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
您需要熟悉AJAX。使用mozilla学习中心了解XMLHttpRequest。在您可以使用基本的XHR对象之后,您很可能希望使用一个好的AJAX库而不是手动编写跨浏览器的AJAX请求(例如,在IE中,您需要使用ActiveXObject而不是XHR)。 jQuery中的AJAX非常棒,但如果您不需要其他所有 jQuery 优惠,请在此处找到一个好的AJAX库:http://microjs.com/。您还需要熟悉node.js文档,找到 here 。在http://google.com搜索一些优秀的node.js服务器和静态文件服务器教程。 http://nodetuts.com是一个很好的起点。
更新:我已将response.sendHeader()
更改为上面代码中的新response.writeHead()
!!!
答案 1 :(得分:29)
Express使这种东西非常直观。语法如下所示:
var app = require('express').createServer();
app.get("/string", function(req, res) {
var strings = ["rad", "bla", "ska"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
})
app.listen(8001)
http://expressjs.com/guide.html
如果你在客户端使用jQuery,你可以这样做:
$.get("/string", function(string) {
alert(string)
})
答案 2 :(得分:5)
我面临以下错误:代码(nodejs 0.10.13),由&符号提供:
access-control-allow-origin 不允许来源
问题已解决,正在改变
response.writeHead(200, {"Content-Type": "text/plain"});
到
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
答案 3 :(得分:0)
以下是您要完成的功能的完整功能示例。我在hyperdev而不是jsFiddle中创建了示例,以便您可以看到服务器端和客户端代码。
查看代码: https://hyperdev.com/#!/project/destiny-authorization
查看工作申请表:https://destiny-authorization.hyperdev.space/
此代码为get请求创建一个处理程序,该请求返回一个随机字符串:
app.get("/string", function(req, res) {
var strings = ["string1", "string2", "string3"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
});
然后,这个jQuery代码发出ajax请求,并从服务器接收随机字符串。
$.get("/string", function(string) {
$('#txtString').val(string);
});
请注意,此示例基于Jamund Ferguson的答案代码,所以如果您发现这个有用,请务必同时支持他。我只是觉得这个例子可以帮助你看看所有东西是如何组合在一起的。
答案 4 :(得分:-1)
RESTful API(路由):
rtr.route('/testing')
.get((req, res)=>{
res.render('test')
})
.post((req, res, next)=>{
res.render('test')
})
AJAX代码:
$(function(){
$('#anyid').on('click', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'GET',
contentType: 'application/json',
success: function(res){
console.log('GET Request')
}
})
})
$('#anyid').on('submit', function(e){
e.preventDefault()
$.ajax({
url: '/testing',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
info: "put data here to pass in JSON format."
}),
success: function(res){
console.log('POST Request')
}
})
})
})