fix: add authentication token to server requests in AddServerForm and EditServerForm

This commit is contained in:
samanhappy
2025-04-13 11:28:13 +08:00
parent 703757165d
commit 2b88e956c0
2 changed files with 19 additions and 11 deletions

View File

@@ -19,9 +19,13 @@ const AddServerForm = ({ onAdd }: AddServerFormProps) => {
const handleSubmit = async (payload: any) => {
try {
setError(null)
const token = localStorage.getItem('mcphub_token');
const response = await fetch('/api/servers', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
'x-auth-token': token || ''
},
body: JSON.stringify(payload),
})
@@ -45,12 +49,12 @@ const AddServerForm = ({ onAdd }: AddServerFormProps) => {
onAdd()
} catch (err) {
console.error('Error adding server:', err)
// Use friendly error messages based on error type
if (!navigator.onLine) {
setError(t('errors.network'))
} else if (err instanceof TypeError && (
err.message.includes('NetworkError') ||
err.message.includes('NetworkError') ||
err.message.includes('Failed to fetch')
)) {
setError(t('errors.serverConnection'))
@@ -71,9 +75,9 @@ const AddServerForm = ({ onAdd }: AddServerFormProps) => {
{modalVisible && (
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
<ServerForm
onSubmit={handleSubmit}
onCancel={toggleModal}
<ServerForm
onSubmit={handleSubmit}
onCancel={toggleModal}
modalTitle={t('server.addServer')}
formError={error}
/>

View File

@@ -12,13 +12,17 @@ interface EditServerFormProps {
const EditServerForm = ({ server, onEdit, onCancel }: EditServerFormProps) => {
const { t } = useTranslation()
const [error, setError] = useState<string | null>(null)
const handleSubmit = async (payload: any) => {
try {
setError(null)
const token = localStorage.getItem('mcphub_token');
const response = await fetch(`/api/servers/${server.name}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
'x-auth-token': token || ''
},
body: JSON.stringify(payload),
})
@@ -41,12 +45,12 @@ const EditServerForm = ({ server, onEdit, onCancel }: EditServerFormProps) => {
onEdit()
} catch (err) {
console.error('Error updating server:', err)
// Use friendly error messages based on error type
if (!navigator.onLine) {
setError(t('errors.network'))
} else if (err instanceof TypeError && (
err.message.includes('NetworkError') ||
err.message.includes('NetworkError') ||
err.message.includes('Failed to fetch')
)) {
setError(t('errors.serverConnection'))
@@ -62,7 +66,7 @@ const EditServerForm = ({ server, onEdit, onCancel }: EditServerFormProps) => {
onSubmit={handleSubmit}
onCancel={onCancel}
initialData={server}
modalTitle={t('server.editTitle', {serverName: server.name})}
modalTitle={t('server.editTitle', { serverName: server.name })}
formError={error}
/>
</div>