MountainConqueror
MountainConqueror

Reputation: 602

How to read data from POST, test it with a condition and send a response back

I'm looking for an easy solution to front-end and back-end communication.

I want to write simple JS front-end client where a user can put a number between 1 an 10 000 to guess the number that server has generated.

So the client job is to send number that user is guessing. The server should test if secretNumber is higher or lower then that provided by the user and it should send back that info.

For now, my server only sends that secret number. I'm getting it inside my client console, so the connection is working.

My question is how should I modify my server code to read the number value from request, test it and then send the right response (example -> your number is higher than the secretNumber)?

This is my server:

const express = require('express');
const app = express();
const cors = require('cors');

app.use(cors());

app.use((request, response, next) => {
  console.log(request.headers);
  next();
});

app.use((request, response, next) => {
  request.secretNumber = Math.floor(Math.random() * 10000) + 1;
  next();
});


app.get('/', (request, response) => {
  response.json({
    secretNumber: request.secretNumber
  });
});

app.listen(3001, () => console.log("Listening on 3001"));

Here is my front-end JS code (I'm using axios):

export function guessNumber(guessValue) {
  return dispatch => {
    dispatch({ type: GUESS_NUMBER });
    axios
      .post('/guess', {
        isNumber: guessValue,
      })
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
  };
}

And I was here looking for answer, but maybe I'm to inexperiened and I need some real example...

Upvotes: 0

Views: 233

Answers (1)

hugomarisco
hugomarisco

Reputation: 336

First you need to persist the secretNumber between requests. At the moment you are generating a new value on each request.

Assuming just one client using the backend concurrently, you can do this by generating the secretNumber when the server starts and keep it in memory (assign it to a variable).

Then you can simply use route params to capture the client's guess:

app.get('/guess/:guess', (request, response) => {
  const guess = params.guess;

  // compare guess with secretNumber and respond accordingly
});

Alternatively you can use the request's body (https://expressjs.com/en/4x/api.html#req.body) instead of route params.

Upvotes: 1

Related Questions