1

I am using axios to send information from my React app to my express API, and when I print the typeof a value before I send the information, it is a boolean (which I do have it typed as) but when I receive it in my API and print the typeof, it is converted to and stored as a string.

the type as it it typed in both the API and the React app:

export interface questionAsked {
  text: string;
  answerGiven: answers[];
}
export interface answers {
  isCorrect: boolean;
  text: string;
}

How I send the information from my React app:

 const [APIResonse, setAPIResponse] = useState<number>(0);
  const sendAnswersAndTime = async (): Promise<void> => {
    try {
      const response = await axios.post("http://localhost:3000/updateAnswers", {
        params: {
          username: "1234",
          questionAsked: questionsAsked,
        },
      });
      const { data } = response;
      setAPIResponse(data);
    } catch (error) {
      console.log(error);
    }
  };
  useEffect(() => {
    sendAnswersAndTime();
  }, []);

How I receive the information in the API

I now have

app.use(express.json());
app.use(cors());
app.post("/updateAnswers", async (req, res) => {
  const topicName = req.body.topicName;
  const clientNumber = req.body.username;
  const questionAsked = req.body.questionAsked;

  console.log(questionAsked, " hello ");

to which it is now undefined. Why would this be returning undefined?

What I have tried is using JSON.stringify and then JSON.parse, this did not work and I also attempted to simply change this axios request from GET to POST and this caused the app to crash.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
javaloaf
  • 13
  • 5
  • 4
    Query parameters are all serialised to strings and treated as such by Express. If you want a boolean at the other end, _parse it_. (But also that endpoint seems pointless, and based on the description probably shouldn't be a GET.) – jonrsharpe Aug 30 '23 at 14:51

1 Answers1

0

Query parameters are always strings. You can either explicitly parse it (see https://stackoverflow.com/a/264037/2422776 for additional details):

const questionAsked = (req.query.questionAsked === 'true'); 

Or, as you suggested, serialize the request in a JSON body.

On the client side, use a POST request. Note that the second argument of psot isn't the config object, but the data directly. You should not have a params entry there, just the variables you want to pass to the server:

const response = await axios.post("http://localhost:3000/updateAnswers", {
    username: "1234",
    questionAsked: questionsAsked,
});

And on the server side have a POST route that handles JSON bodies:

app.use("/updateAnswers", express.json());
app.post("/updateAnswers", async (req, res) => {
  const clientNumber = req.body.username;
  const questionAsked = req.body.questionAsked;

  res.send("Answers updated succesfully");
});
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • I now have app.post("/updateAnswers", async (req, res) => { const topicName = req.body.topicName; const clientNumber = req.body.username; const questionAsked = req.body.questionAsked; console.log(questionAsked, " hello "); to which it is now undefined. I have a body parser: app.use(express.json()); app.use(cors()); why would this be returning undefined? – javaloaf Aug 30 '23 at 15:18
  • @javaloaf please edit your question and add this code in a properly formatted block. It's impossible to read it like this in the comments. – Mureinik Aug 30 '23 at 15:19
  • done, sorry about that! – javaloaf Aug 30 '23 at 15:22
  • @javaloaf your second argument in the `post` call is wrong - you don't need `params` under it, just the parameters directly. See my answer for an example. – Mureinik Aug 30 '23 at 15:25
  • 1
    this worked. thank you so much! – javaloaf Aug 30 '23 at 15:37