You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS中带Basic认证的GET请求报401及语法错误求助

问题分析与修复方案

核心问题

你遇到的401未授权和解析错误,根源是两个关键代码问题:

  1. Basic认证字符串拼接错误:
    你用单引号包裹${username}:${password},这会把字面量字符串传给encode函数,而非实际的用户名密码组合。模板字符串必须用反引号(`)才能实现变量拼接。

  2. no-cors模式导致响应无法解析:
    设置mode: 'no-cors'后,浏览器会返回不透明响应,无法读取内容,调用res.json()自然会抛出"Unexpected end of input"错误。除非完全不需要处理响应,否则不要使用该模式。

修复后的代码

import React, { Component } from 'react';
import { encode } from "base-64";

export class MyDates extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      isLoaded: false,
    }
  }

  componentDidMount() {
    const url = 'https://gd.xxxxxx.com.tr/api/Dates';
    const username = 'xxxxxxx';
    const password = 'Bxxxxxxxxx';

    fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': 'Basic ' + encode(`${username}:${password}`)
      }
    })
    .then(res => {
      // 先校验响应状态,避免认证失败时继续解析
      if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`);
      return res.json();
    })
    .then(json => {
      this.setState({
        isLoaded: true,
        items: json,
      })
    })
    .catch(err => {
      // 添加错误处理,避免页面一直处于加载状态
      console.error('请求出错:', err);
      this.setState({ isLoaded: true });
    })
  }

  render() {
    const { isLoaded, items } = this.state;
    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className='container'>
          <h3>Randevularım sayfası</h3>
          <div className='row'>
            {items.map(item => (
              <div className='col-md-4 px-4 py-2' key={item.MAHALLEID}>
                <div className='m-2 rounded' style={{ background: '#e2e2e2' }}>{item.MAHALLE}</div>
              </div>
            ))}
          </div>
        </div>
      )
    }
  }
}

额外优化建议

  • 增加错误捕获:代码中添加了.catch()逻辑,请求失败时会更新状态并打印错误,避免页面一直停留在加载状态。
  • 移除冗余请求头:GET请求通常不需要设置Content-Type: application/json,除非API明确要求。
  • 变量声明规范:用const替代let声明不会重新赋值的变量,代码更严谨。

内容的提问来源于stack exchange,提问作者sinaia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:54:22