[英]nodejs hapiJs: Sending, receiving data from client
我有以下文件; 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
。 訪問請求數據時,需要指定它是否在查詢中,有效負載中等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.