How do i react to xmlHttpRequest?

Hi, i have this in client:

var data = new FormData();
data.append("content", "hello");
var xhr = new XMLHttpRequest();
xhr.open("POST", "my-project.glitch.me");
xhr.send(data);

how do i set that if server receive “hello” then it send response “hi” to client?

also im not sure how do i get response from server…
i think its:

xhr.open("GET", "my-project.glitch.me")

im new to all this so sorry for stupid question

1 Like

Hi! Welcome to the community!

There’s no such thing as a stupid question here :slight_smile:

Ok, first I will try to answer your question. XMLHttpRequest (XHR for short) is known to be a bit hard to work with, but I think what you need is like this:

var data = new FormData();
data.append("content", "hello");
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", handleResponse); // This is the new line
xhr.open("POST", "my-project.glitch.me");
xhr.send(data);

function handleResponse() {
  // In this function, 'this' is an XMLHttpRequest object
  // Do something with the response here
  console.log(this.status, this.responseText);
}

You attach a listener function before sending the request.

Above, we use this.responseText which should have the response data from the POST in it. But there are other properties you can check, to get the HTTP Status for example, and there’s a list here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

Check out these docs on MDN: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Now, a lot of people swerve XHR altogether. A modern alternative is Fetch, which is built into most modern browsers as a replacement for XHR. Here’s a good intro to fetch: https://javascript.info/fetch

You can also use a library. In the old days, jQuery was popular for it’s ajax functions that do what you want. A more modern alternative is axios but adding it into your project is left up to you :slight_smile:

Hope this helps. Here to answer more questions when I can :slight_smile:

1 Like

Hello @azari :wave: Welcome to Glitch!

What you are trying to do is referred to as communication between a client and an API. Thus requires a front-end and a back-end.

I recommend you have a look at the Fetch API to send requests from the browser to a server. If your API returns JSON data I recommend you have a look at Axios, which I’ll be using in my examples below.

A simple example between a client-server relationship in code could look like this:

app.js (server-side)

// Import express
const express = require("express");

// Create an application
const app = express();

// Add a static site middleware. This allows
// the browser to request files like `index.html`
app.use(express.static(__dirname + "/public"));

// Add a ping route.
app.get(
  // This is the route of which the
  // browser can request a "pong"
  // response.
  "/ping",
  // This is the middleware used to respond
  // to the client, you can think of this
  // like the route handler.
  async (req, res) => {
    // Send a JSON response to the client.
    res.json("pong!");
  }
);

// Start your server.
app.listen(3000, () => console.log("🚀 Server is running at port 3000."));

client.js (client-side)

// A ping function to send a request to
// the ping route.
const ping = async () => {
  const { data } = await Axios.get("/ping");
  return data;
};

// Call the ping function:
ping()
  // Since the ping function
  // returns a promise we must
  // use .then() and .catch()
  // to get the responses.
  .then(data => console.log("Server said:", data))
  .catch(error => console.error("Server failed:", error));
2 Likes

Axios needs to be included separately in the client side file (using a script tag) , right?

It can also be included using ES6 imports.

I’m a bit new to this, how can I use Axios on the client-side?
I’m trying to send form data so my server.js can store those details somewhere (the “action” attribute with the “POST” method didn’t work) and Axios isn’t defined on the client so I can’t use it, unless I could somehow define it within my client.js still?

Hey @Un-index,

You can use Axios on the client-side by including this script tag before your closing </head> tag:

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Hope this helps!

2 Likes

I can’t use this through an external client.js script then, and can only use it client-side through using the script tag within HTML?

@Un-index, the answer is yes; you can.

If you load your client.js file after you load the Axios script tag, you will be able to use Axios in your client.js.

In case you’re wondering what I meant,

<script src="/client.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Then, in your client.js, you should be able to use Axios just fine.

1 Like

HTML file:

sign up.js:


(error)

What am I doing wrong? It says Axios is not defined.

Perhaps this is an XY problem sprouting, all I need to do is send a string so that server.js can store that sent data, is this the best way to go about this?

@Un-index, you can ignore the warning shown in the editor, it’s because of the code linting tool user by Glitch not detecting global variables.

2 Likes

I usually code using glitch but I’m not very smart when it comes to HTTP Requests.
I plan on using this feature but I always end up with this error.
image

This is my Code:

var xhr = new XMLHttpRequest()

XHR doesn’t work on Node. You should install node-fetch

2 Likes

image
Im still getting the same error and im using
const fetch = require("node-fetch")

Hey there, have you read the node-fetch docs and are using the actual module?

Indeed I am!


Im doing exactly what the doc says.

@Cosmental, can you show us the whole error?