Communication to backend with frontend JS

How do I communicate to backend in frontend JS?

Edit: ethan why the heart

3 Likes

It depends on how you’ve got everything set up.

The two main ways (that I can think of) that you’d configure your back-end (and they are not necessarily mutually exclusive) is to serve an API or to use real-time communications. An API is simpler, so I’ll give you an example of how that might look:

Server:

// basic express server
const express = require("express");
const app = express();

// host a page
app.get(["/", "/Home"], function(req, res) {
	res.sendFile(__dirname + "/path/to/index.html");
});
// or you could just statically host a folder (this will host it at `/`, not `/public/`)
app.use(express.static("public"));

// parse POST body using express
app.use(express.json());

// API
app.post("/api", function(req, res) {
	// req.body should be an object containing the parsed JSON from the post request's body
	console.log(req.body);
	// this example API just returns the JSON sent to it
	res.json(req.body);
});

// start the server
app.listen(8080);

A script somewhere on the client-side:

// an object to send to the server
const object_to_send = {
	boolean: true,
	string: "Hello world!"
};

// use fetch to send request to server
fetch("/api", {
	method: "POST", // post request
	headers: {
		"Content-Type": "application/json" // tell the server we're sending JSON
	},
	body: JSON.stringify(object_to_send) // convert the JSON to a string (required format)
})
	// convert the response to JSON
	.then(function(res) {
		return res.json();
	})
	// do whatever you want with the response
	.then(function(res) {
		console.log("Result:", res);
	});

(I haven’t tested this so I could have overlooked something minor.)

2 Likes

Accidentally set this as solution lol. But this is probably correct though, thanks a lot

2 Likes

Yeah I was surprised that it was instantly marked as solution lol :slight_smile:

1 Like

I made a Repl which demonstrates this code here (it does all work) :slight_smile:

1 Like

It doesn’t work — I’m not using Node.js. I’m using HTML, CSS, JS, so it can’t find require

HTML, CSS & JS is front-end, it’s the client side. The HTML, CSS & JS Repl will need to communicate with a separate server.

1 Like

This worked, thanks.

1 Like

how do I send var from nodejs to html btw? I want to make the res.body into a text tag

Uhh, could you explain that futhermore?

I’m editing my question. How do I use this with websocket? I want it to replicate the message to all the clients, and I don’t think it’s possible with express alone.

1 Like

Just found this on a quick google search: express-ws - npm
Hope this helps!

2 Likes

Any idea how this works lol? I can’t understand the example, it says app.ws but app value is express()

1 Like
const express = require("express");
const app = express();
var expressWs = require('express-ws')(app);

I am no js expert but I think that is how you would do it.

Edit: I just found that they already put this in the example, I guess I should read more…

1 Like

Wait, so app functions as a server? I’m very confused

1 Like

The app is the server I think, app.listen is the webserver listening for http requests.

1 Like

But which one is the websocket server?

1 Like

I think it’s kind of like an extension, itself does nothing, but adds features like app.ws. So now that you required and added the ws extension, app is both the normal server and the web socket server. (Don’t take my word on any of this)

1 Like

hello, can I just multiplayer? i am very confused now. sorry for the bother

1 Like

I might not be the best person for this, but I guess I can.

1 Like