0

I'm trying to send token to my backend server to let it verify the token with Google recaptcha. However, my frontend does not seem to connect with my backend.

Error Message I'm getting: POST http://localhost:3000/post 404 (Not Found) Apparently, my FE could not find the port to BE.

I have tried to use frontend for API request with the URI provided by google but I ran into CORS issue, and it is not secure.

By console.log(token), I find nothing wrong with the library itself because I have successfully get a success response from Google using the token with POSTMAN.

Here is my frontend:

    const handleVerify = async (token) => {
        console.log(token)
        const captchaToken = token;

        await axios.post("/post", { captchaToken })
            .then(res => console.log(res)
                .catch((error) => {
                    console.log(error)
                }))

        setIsVerified(true)
        setActiveStep(activeStep + 1);
    }

.....
       <ReCAPTCHA
            ref={recaptchaRef}
            sitekey={process.env.REACT_APP_SITE_KEY}
            onChange={(token) => handleVerify(token)}
            size="normal"
            onExpired={(expire) => handleShowExpired(expire)}
            >
       </ReCAPTCHA>
.....

Here is my backend:

const express = require("express");
const cors = require("cors");
const axios = require("axios");
const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);

//POST route
router.post("/post", async (req, res) => {
    const { captchaToken } = req.body;

    //sends secret key and response token to google
    await axios.post(
        `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SECRET_KEY}&response=${captchaToken}`
    );

    //check response status and send back to client
    if (res.data.success) {
        res.send("Human");
    } else {
        res.send("Robot");
    }
});
AnthonyDev220
  • 669
  • 5
  • 17

1 Answers1

0

If your server runs on port 5000 you should await axios.post("http://localhost:5000/post", { captchaToken })

Also, you have to validate the axios response.

router.post("/post", async (req, res) => {
    const { captchaToken } = req.body;

    //sends secret key and response token to google
    const axiosResponse = await axios.post(
        `https://www.google.com/recaptcha/api/siteverify?secret=${process.env.SECRET_KEY}&response=${captchaToken}`
    );

    //check response status and send back to client
    if (axiosResponse.data.success) {
        res.send("Human");
    } else {
        res.send("Robot");
    }
});
NicoIama
  • 11
  • 2