gpt4 book ai didi

javascript - nodejs hapiJs : Sending, 从客户端接收数据

转载 作者:行者123 更新时间:2023-11-30 10:12:17 25 4
gpt4 key购买 nike

我有以下文件; client.js 和 server.js。我想使用 ajax 将数据发送到我的服务器。我设法发送了搜索到的用户名,但在服务器上收到的域未定义。我不确定我是否在客户端、服务器端或两者都遗漏了什么?在服务器端,我的函数应该是一个通用函数,以允许它接收任何域并在该域上发出请求。有人可以帮忙吗?

客户:

$(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;

最佳答案

req.domain.domainName 更改为 req.query.domainName。当你访问请求数据时,你需要指定它是否在查询中,在负载中等。

关于javascript - nodejs hapiJs : Sending, 从客户端接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com