【发布时间】:2018-06-07 08:34:07
【问题描述】:
尽管我已经在本地服务器上学习并使用 Node 实现了 AJAX 请求。我发现我在本地服务器上创建的请求在云服务器上不起作用。
当我使用 AJAX 向服务器(Node)请求数据时,由于 URL 的原因(或者我认为是),请求没有到达服务器。
节点代码:
app.get("/",function(req,res){
app.use(express.static(__dirname + '/'));
app.get("/mypath/",function(req,res){
console.log("please tell me that you arrive here"); //This actually never happens
//some functions using the data in "req" and putting there in var "data"
res.send(data);
});
});
Javascript 代码:
$.ajax({
url: 'http://localhost:3000/mypath/',
type: 'GET',
data: {//some data to use on the server},
dataType: "json",
complete: function(data){
//some stuff with the transformed data
},
});
上面的代码在本地服务器(我的电脑)中工作。但不是在云中,我在尝试使用 NGINX 和 Express 处理服务器静态文件时遇到了一些问题,但我能够解决。
您认为考虑到我提供静态文件的方式以及我在云服务器中工作的方式,当我们尝试通过 URL 进行通信时,我应该以不同的方式使用 AJAX 请求吗?
控制台日志:
Console Log after using Marcos solution
编辑:来自 jQuery AJAX 和节点请求的代码
节点设置:
var express = require('express');
var app = express();
var request = require("request");
var db = require('mysql');
const path = require('path');
var http = require("http").Server(app);
var io = require("/usr/local/lib/node_modules/socket.io").listen(http);
http.listen(3000, 'localhost'); //At the end of everything between here and the code.
获取节点代码:
app.use(express.static(__dirname + '/'));
app.get('/reqData',function(req,res){
//I never arrive here
console.log("print that I am here");
transform(req.query.selection1,req.query.selection2,function(){
res.json(data); //data is transformed globally
});
});
阿贾克斯:
function requestData(){
$.ajax({
url: 'http://localhost:3000/reqData',
type: 'GET',
data: {//Some stuff to send},
dataType: "json",
complete: function(data){
do(data);
},
error: function(e){
console.log(e);
}
});
}
新控制台日志: Chrome Console Error
【问题讨论】:
-
url在您的$.ajax请求调用中不是有效的绝对 URL。这是您使用的实际网址吗? -
无论您在何处执行,您的 URL 都不正确。至少应该是
url: 'http://localhost:3000/mypath/' -
此外,您应该始终做的第一件事是在浏览器的控制台中查找错误。你看到了吗?
-
嗨@Jacob,源代码中的url是正确的,问题仍然存在。
-
嗨@Phil,源代码中的url是正确的,问题仍然存在。
标签: javascript node.js nginx