0

Despite I have learned and implemented AJAX request with Node on my local server. I am finding that the requests that I created on my local server, just does not work at cloud server.

When I use AJAX to request data to the server (Node), the request does not get to the server because of the URL (or I think so).

Node Code:

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 Code:

$.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
        },
    });

The code above works in the local server (my pc). But not in the cloud one, I had some problems trying to the server static files with NGINX and Express, but I was able to figure it out.

Do you think that given the way I am serving the static files and that I am working in the cloud server, I should use AJAX request in a different way when we are trying to communicate through an URL?

Console Log:

Console Log after using Marcos solution

EDIT: Code from jQuery AJAX and Node Request

Node Set-Up:

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.

GET Node 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  
                });

});

Ajax:

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);
            }
       });

    }

New Console Log: Chrome Console Error

1 Answers1

2

The main issue you have, is how you're defining your routes, you will be unable to reach /mypath/ until you perform a request first to /.

You should not define your routes that way, each route should be defined individually, and not in a nested way.

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.
});

And your route app.get('/') conflicts with express.static(__dirname + '/'), so you should just remove it if you're only serving an index.html file, which seems to be your case.

Then in your $.ajax you should add the protocol to the URL.

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

Now, supposing you have everything else setup correctly, you will be able to access /mypath

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Hi Marcos, if I do not put the express.static inside the app.get, I am not able to make app.get("/"... work. I do not know why it is happening. – Carlos Andrés Castro Marín May 31 '18 at 22:09
  • Explain what does: `I am not able to make app.get work` means. Have you put `res.send('foo')` inside `app.get("/")` and see if you get that response? – Marcos Casagrande May 31 '18 at 22:11
  • Hi, yes, I have a res.sendFile(__dirname + "/index.html"); But into an IF (because I am checking req.sesision.visitor), I do not know if using cookies and cookie-parser is changin anything. – Carlos Andrés Castro Marín May 31 '18 at 22:24
  • I have seen that if I put express to serve static files outside "app.get", then app.get("/") does not happen never. – Carlos Andrés Castro Marín May 31 '18 at 22:30
  • Check updated answer, your route conflicts with `express.static` just remove `app.get('/')` which you don't need. – Marcos Casagrande May 31 '18 at 22:39
  • Perfect Marcos, however, I does not make any conflict with the cookies? This since I am using req.session.visitor to assing the sessions. I am doing it the wrong way? – Carlos Andrés Castro Marín May 31 '18 at 23:03
  • You should set the cookies in another middleware, before `express.static`, check updated answer – Marcos Casagrande May 31 '18 at 23:05
  • Thanks Marcos. I've done that. However it seems that I am not able to serve static files with that solution, could you please check at the log I attached to my question? it is at the end. – Carlos Andrés Castro Marín Jun 01 '18 at 03:00
  • The solution works perfectly, I'm testing it right now, you probably don't have an `index.js` at the root of your app. Post your full express code & your directory structure. – Marcos Casagrande Jun 01 '18 at 03:04
  • Marcos, everything is in the root (even the index.js file that I do have). Right now I do not have a directory structure, just a index.html, server.js and index.js in my root, another couple of files. I will see the way to put all the express code here. Thanks a lot. – Carlos Andrés Castro Marín Jun 01 '18 at 03:17
  • Hi Marcos, I checked and I am not able to serve static files as my index.js if I add the express.static after app.get('*'). Only serves it if I add it before the app.get. – Carlos Andrés Castro Marín Jun 01 '18 at 18:33
  • Have you added the next(); function call? And add your code if you want further help, I cannot guess your code. The code I. Provided works fine. – Marcos Casagrande Jun 01 '18 at 18:46
  • Yes I did, ok I will upload the code and let you know. Marcos, what do you think is the best middleware to use sessions? I am using right now express-session and cookie-parser. – Carlos Andrés Castro Marín Jun 01 '18 at 19:02
  • Those two are just fine. – Marcos Casagrande Jun 01 '18 at 19:09
  • Hi @Marcos, it seems that the problem is solved for the cookies and the static files, however the problem about the route persists, do you think it is better to open a new question or do you prefer me to update this question? – Carlos Andrés Castro Marín Jun 06 '18 at 23:44
  • Hi, Since it's out of scope of this question, please open a new question, it will also attract more users that may be able to help you. But please leave a link here so I can take a look. Don't forget to accept the answer here :) – Marcos Casagrande Jun 06 '18 at 23:46
  • Hi Marcos, actually I read the question again and you helped to solve something that wasn't the scope of the question, and thank you very much. I have added the missing code you suggested to see if may be I am doing something wrong. Do you think the configuration of nginx have you be posted too? Thanks. – Carlos Andrés Castro Marín Jun 07 '18 at 00:35
  • Understood. I will accept your answer is correct (thing that I do not know how to do by the way). And open a new question with the edited part. Hopefully you will be able to comment on my mistakes. Thanks again. – Carlos Andrés Castro Marín Jun 07 '18 at 00:53
  • Hi Marcos, as promised, I am sending the new link with the new question. Finally, I have accepted your answer. https://stackoverflow.com/questions/50826861/jquery-ajax-get-request-does-not-arrive-to-node-js-using-nginx – Carlos Andrés Castro Marín Jun 12 '18 at 22:47