使用 NGINX 时,无法在 Node 下使用 AJAX 发出 GET 请求.js



尽管我已经在本地服务器上学习并使用Node实现了AJAX请求。我发现我在本地服务器上创建的请求在云服务器上不起作用。

当我使用 AJAX 向服务器(节点(请求数据时,由于 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 请求?

控制台日志:

使用马科斯解决方案后的控制台日志

编辑:来自jQuery AJAX和Node Request的代码

节点设置:

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 控制台错误

您遇到的主要问题是您如何定义路由,在您首先执行请求之前,您将无法到达/mypath//

您不应该以这种方式定义路由,每个路由都应该单独定义,而不是以嵌套的方式定义。

app.get('*', (req, res, next) => {
// Set your cookies here, or whatever you want
// This will happen before serving static files
next(); // Don't forget next.
});
app.use(express.static(__dirname + '/'));
app.get('/mypath/', (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); // make sure it is defined.
});

而且您的路由app.get('/')冲突express.static(__dirname + '/'),因此如果您只提供index.html文件,则应将其删除,这似乎是您的情况。

然后在您的$.ajax中,您应该将协议添加到 URL。

$.ajax({
url: 'http://yourdomain.com/mypath/',
// url: 'http://localhost:3000/mypath/',
/* ... */
});

现在,假设您正确设置了其他所有内容,您将能够访问/mypath

最新更新