如何解决ASP.NET Core+React登录时的XMLHttpRequest无效URL异常
ASP.NET Core + React 登录时无效URL错误的解决
问题现象
在Visual Studio中开发基于ASP.NET Core和React.js的应用,点击登录按钮后持续触发以下错误:
DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL at dispatchXhrRequest (http://localhost:44421/static/js/bundle.js:72972:13)
相关代码
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> ) }
Axios配置代码
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), }; }
问题原因
错误核心是URL拼接格式错误:BASE_URL定义为'http://localhost:5269'(末尾无斜杠),拼接时直接和'api/'相连,最终生成的URL是http://localhost:5269api/participant/——这是不符合HTTP规范的无效URL,导致XMLHttpRequest无法正常打开连接。
解决方案
两种修复方式二选一即可:
方式一:修改BASE_URL末尾添加斜杠
将Axios配置中的BASE_URL改为:
export const BASE_URL = 'http://localhost:5269/';
方式二:修改URL拼接逻辑,在BASE_URL和api之间添加斜杠
使用模板字符串优化拼接逻辑,避免手动拼接错误:
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}`), }; }
修复后生成的正确URL为http://localhost:5269/api/participant/,即可正常发起登录请求。
内容的提问来源于stack exchange,提问作者Simbarashe Nyaruwata
相关产品推荐
相关产品推荐

