So I just started trying out some light back-end developing for the first time using express. And I want to call a POST request from a html/js file, and I found how to do it with Jquery. However I would like to know how you can do the exact same thing in pure javascript. Here is the code I have in Jquery:
---Server---
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
const greens = {"orange"}
app.get("/greens", (req, res) => {
res.json(greens);
});
app.post('/greens', (req,res) => {
var itemName=req.body.itemName;
console.log("name = "+itemName);
res.end("yes");
});
app.listen(3000, "localhost", () => {
console.log("the server is up and running! http://localhost:3000/greens");
});
---JS File---
$(document).ready(function(){
var itemName;
$("#submit").click(function() {
let Name = "banana";
$.post("http://localhost:3000/login",{itemName: Name}, function(data){
});
});
});
ps. The HTML code I have is only a button with the id "submit". pps. I know the code doesn't really do anything, but I just want to know how to translate the jquery to javascript, nothing else.
Solved using fetch!
fetch("http://localhost:3000/login",
{
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({itemName: "user"})
});