Ajax in express JavaScript server

1

Good morning, I have a server in javascript express with which I deploy a websocket server.

Now I need to receive a signal by websocket send me this data to a PHP, I researched and the best option is to send it by ajax but to include that line generates the following error

$.ajax({
 ^ReferenceError: $ is not defined
at Socket.<anonymous> (C:\xampp\htdocs\app.js:25:6)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at C:\xampp\htdocs\node_modules\socket.io\lib\socket.js:528:12
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

So I have to include the JQuery library to the Javascript file but I do not know how it can be included.

The full code of the express server is as follows.

var express = require("express");
var app = express();

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

var server = app.listen(3000,'0.0.0.0',function(){
    console.log("App server up and running on %s and port %s",server.address().address ,server.address().port);
});

var io = require('socket.io')(server);

io.on('connection',function(socket){
    socket.emit('welcome_event', { info: 'world' });

    socket.on('response_evet',function(data){
      //Que guarde en un txt en la misma ruta de este archivo
      /*El objeto param contendrá los datos que mandarás al servidor para procesarlos*/
     var param = {
         mensaje: data
     };

     $.ajax({
        data: param,
        url: "saveFile.php",
        method: "post",
        success: function(data) {
          /*La variable data contiene la respuesta de tu script PHP*/
        }
     });

     console.log("Data desde el cliente",data);
    });
});

How could Ajax be included in this file, thanks.

    
asked by Jorge Reinaldo Linares Pineda 15.12.2018 в 17:34
source

2 answers

0

instead of Ajax with jquery, you can use Fetch which is the way to do it without jquery and it is very simple to use:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

link

    
answered by 15.12.2018 в 17:49
0

Inluyelo, downloading from NPM, as follows

npm install -S jquery

Later in your file js you just require it in this way

const jquery = require('jquery')

If you want to verify the installation, send to print from console the constant just created in this way:

console.log(jquery)

Which gives you a message similar to this one:

[Function]

Already with that you should have to serve within your file

Here the original source

link

    
answered by 15.12.2018 в 17:40