1

I writirng server in Express to posibility GET and POST. In Insomnia I get and post valid data.

This is code my REST.

const express = require('express');
const app = express();
const port = 3000;
var cors = require('cors');

app.use(express.json()) 
app.use(express.urlencoded({extended: true}))
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({extended: true}));

let myValue = 1;

app.listen(port, () => {
 console.log(`Server running on port ${port}`);
});

//GET

  app.get('/get', (req, res) => {
    return res.json({"wartosc": myValue})
});

//POST

app.post('/post', function (req, res) {
  myValue = req.body.value;
  console.log(req.body)
  return res.json({"wartosc": myValue});
});

Then I creaeted page with two input will be used to call the GET and POST methods of our REST server.

async function getMethod() {
    let inputValue = document.getElementById("inputValue").value;
    const responseGet = await fetch('http://localhost:3000/get');
    const myJsonGet = await responseGet.json();
    //console.log(JSON.stringify(myJsonGet));
    document.getElementById("inputValue").value = myJsonGet.wartosc;
}

async function postMethod(){
    let inputValue = document.getElementById("inputValue").value;
    let responsePost = await fetch('http://localhost:3000/post', {
        method: 'POST',      
        body: {'value' : JSON.stringify(inputValue)}
      });

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="inputValue">
    <button onclick="getMethod()"> GET</button>
    <button onclick="postMethod()">POST</button>


    <script src="script.js"></script>
</body>
</html>

When I do get , I get the correct value, but when I change the value and send a post, the server prints undefined.

I don't know why, will you try to help me?

student_it
  • 79
  • 7

2 Answers2

1

In your script.js postMethod() you should stringify the entire body: body: JSON.stringify({'value' : inputValue}) Ideally you use querystring.stringify instead but this should also work fine.

Alternatively, you can just leave out the entire script.js with the async stuff. Instead try with using a form and name="value". You can change the form action and method per button.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <form method="GET" action="http://localhost:3000/get">
        <input type="text" id="value" name="value">
        <button type="submit">GET</button>
        <button type="submit" formmethod="post" formaction="http://localhost:3000/post">POST</button>
    </form>
</body>

</html>
bdbdbd
  • 416
  • 5
  • 13
0

I did some changes to make it work on CodeSandbox (example). Everything works.

const express = require("express");
const app = express();
const port = 3000;
var cors = require("cors");

const rand = () =>
  Math.random()
    .toString(36)
    .substr(2);

app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

//GET
app.get("/get", (req, res) => {
  return res.json({ getval: rand() });
});

//POST
app.post("/post", function(req, res) {
  return res.json({ postval: `${rand()}:${req.body.value}` });
});

I put HTML and JavaScript files in the public directory.

async function getMethod() {
  const responseGet = await fetch("/get");
  const myJsonGet = await responseGet.json();
  document.getElementById("inputValue").value = myJsonGet.getval;
}

async function postMethod() {
  let inputValue = document.getElementById("inputValue").value;
  let options = {
    method: "POST",
    body: JSON.stringify({ value: inputValue }),
    headers: {
      "Content-Type": "application/json"
    }
  };
  let responsePost = await fetch("/post", options);
  let myJsonPost = await responsePost.json();
  document.getElementById("inputValue").value = myJsonPost.postval;
}

Both when you send JSON data via GET and POST, you must extract it with response.json(). In addition, when submitting POST data, you must set a header that is JSON. Without it, the server will not recognize that the transmitted data is in this format.

Gander
  • 1,854
  • 1
  • 23
  • 30