我有以下文件; client.js和server.js。我想使用ajax将数据发送到我的服务器。我设法发送搜索到的用户名,但在服务器上收到的域名未定义。我不确定我是否在客户端或服务器端丢失了某些内容,或者两者兼而有之? 在服务器端,我的函数应该是一个通用函数,以允许它接收任何域并在该域上发出请求。 有人可以帮忙吗?
Cliente:
$(document).ready(function(){
console.log("Ready!");
var domains=[ ]; //pass domain names into array for easier iteration
domains.push($(".facebook").find("a").text());
domains.push($(".github").find("a").text());
domains.push($(".twitter").find("a").text());
domains.push($(".instagram").find("a").text());
domains.push($(".pinterest").find("a").text());
console.log(domains);
$("#searchbutton").on('click', function(event){
var username = $("#searchname").val().trim(); // store value from searchbox
console.log(username);
if(username === ""){
event.preventDefault();
}
if(username){
var newhtml = "<p>";
newhtml += username;
newhtml += "</p>";
$(".username").html(newhtml);
$(".username").remove("newhtml");
var domainCheck = function(domainName){
$.ajax({
url: "/"+username,
type: "get",
data: {domainName: domainName, username: username},
success: function(response){
console.log(domainName);
console.log(response);
}
});
};
//send ajax request to server for each domain name to check for username availability
var len = domains.length;
for(var i = 0; i<len; i++){
domainCheck(domains[i]);
console.log(domains[i]+'\n');
}
}
});
});
服务器:
var Hapi = require('hapi');
var request = require('request');
var server = Hapi.createServer('localhost', 8080);
var routes =[
{
path: "/",
method: "GET",
handler: function (req, reply){
console.log("Home page loaded and runnning!");
reply.file('index.html');
}
},
{
path: '/{username}',
method: 'GET',
handler: function (req, reply){
// this is not working. the domain name is not being received from the client side. instead its passing undefined!
request('http://www.'+ req.domain.domainName +'.com/' + req.params.username, function(error, response, body){
console.log("Request received");
console.log(response.statusCode);
if ( response.statusCode === 404 ) {
console.log( "Username " + req.params.username + " is available on " + req.domain.domains);
reply({"available":"yes"});
}
if ( response.statusCode === 200 ) {
console.log( "Username " + req.params.username + " is already taken on " + req.domain.domains);
reply({"available":"no"});
}
});
}
},
{
method: 'GET',
path: '/static/{param*}',
handler: {
directory: {
path: 'static'
}
}
}
];
server.route(routes);
server.start(function() {
console.log("Server started", server.info.uri);
});
module.exports = server;
答案 0 :(得分:4)
将req.domain.domainName
更改为req.query.domainName
。当您访问请求数据时,您需要指定它是在查询中,在有效负载中等等。