How to resolve DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL

189 Views Asked by At

I have an ASP.NET Core with React.js App in Visual Studio. I'm trying to sign into the app after I run it. But I keep getting the error `DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL at dispatchXhrRequest (http://localhost:44421/static/js/bundle.js:72972:13)

Here is my Login.js

import React from "react"
import { Button, Card, CardContent, TextField, Typography } from "@mui/material"
import { Box } from "@mui/system"
import Center from "./Center"
import useForm from "../hooks/useForm"
import { createAPIEndpoint, ENDPOINTS } from "../api"
import useStateContext from "../hooks/useStateContext"
import { useNavigate } from "react-router"

const getFreshModel = () => ({
    name: '',
    email: ''
})

export default function Login() {

    const { setContext } = useStateContext();
    const navigate = useNavigate();

    const {
        values,
        errors,
        setErrors,
        handleInputChange
    } = useForm(getFreshModel);

     

    const login = e => {
        e.preventDefault();
        if (validate())
            createAPIEndpoint(ENDPOINTS.participant)
                .post(values)
                .then(res => {
                    setContext({ participantId: res.data.participantId })
                    navigate('/quiz')
                })
                .catch(err => console.log(err))
    }

    const validate = () => {
        let temp = {}
        temp.email = (/\S+@\S+\.\S+/).test(values.email) ? "" : "Email is not valid."
        temp.name = values.name !== "" ? "" : "This field is required."
        setErrors(temp)
        return Object.values(temp).every(x => x === "")
    }

    return (
        <Center>
            <Card sx={{ width: 400 }}>
                <CardContent sx={{ textAlign: 'center' }}>
                    <Typography variant="h3" sx={{ my: 3 }}>
                        Quiz App
                    </Typography>
                    <Box sx={{
                        '& .MuiTextField-root': {
                            m: 1,
                            width: '90%'
                        }
                    }}>
                        <form noValidate autoComplete="off" onSubmit={login}>
                            <TextField
                                label="Email"
                                name="email"
                                value={values.email}
                                onChange={handleInputChange}
                                variant="outlined"
                                {...(errors.email && { error: true, helperText: errors.email })} />
                            <TextField
                                label="Name"
                                name="name"
                                value={values.name}
                                onChange={handleInputChange}
                                variant="outlined"
                                {...(errors.name && { error: true, helperText: errors.name })} />
                            <Button
                                type="submit"
                                variant="contained"
                                size="large"
                                sx={{ width: '90%' }}>Start</Button>
                        </form>
                    </Box>
                </CardContent>
            </Card>
        </Center>


    )
}

And here is my Axios configuration

import axios from 'axios';

export const BASE_URL = 'http://localhost:5269';

export const ENDPOINTS = {
    participant: 'participant'
}
export const createAPIEndpoint = (endpoint) => {

    const url = BASE_URL + 'api/' + endpoint + '/';
    return {
        fetch: () => axios.get(url),
        fetchById: (id) => axios.get(url + id),
        post: (newRecord) => axios.post(url, newRecord),
        put: (id, updatedRecord) => axios.put(url + id, updatedRecord),
        delete: (id) => axios.delete(url + id),
    };

}

1

There are 1 best solutions below

1
Luke Woodward On

Have you tried using console.log to log the URLs you are creating in your createAPIEndpoint function?

If you do, you might find that they look something like this:

http://localhost:5269api/participant/

Spot the problem?

You are missing a / after the port number 5269 and before the api. Without the /, the URL is indeed invalid (5269api isn't a valid port number), so it's no surprise that you get an "Invalid URL" error.

To fix the problem, add a / to the end of the value of BASE_URL, or before api/ in createAPIEndpoint.