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

React中使用fetch API创建用户时遭遇401认证错误

问题分析与解决方案

核心问题拆解

  1. no-cors模式导致401:
    用no-cors时,浏览器会强制限制请求的可见性,返回的响应是无法读取的「opaque响应」,还会自动忽略你设置的Authorization等自定义请求头——后端根本收不到Basic Auth凭证,自然返回401未授权。

  2. cors模式触发CORS错误:
    这是因为后端没配置跨域许可,浏览器的同源策略拦截了请求。前端自己加Access-Control-Allow-Origin这类头没用,这些是后端响应头,得后端返回给浏览器才生效。


前端代码修正

删掉没用的请求头,改用默认的cors模式,修正后的代码如下:

const officeId = 1
const locale = "en"
const dateFormat = "dd MMMM yyyy"
const active = false
const pwd = "somevalue"
const user = "somevalue"
// 移除后端才需要设置的Access-Control相关头
let apiHeader =  {
    'Authorization': "Basic " + btoa(user + ':' + pwd), // 浏览器环境用btoa更直接
    "Content-Type": "application/json",
    "Accept": "*/*",
    "X-Fineract-Platform-TenantId": "somevalue",
}
const myUrl = "https://somevalue.com/api/v1/clients"

let clientDetails = {
    firstname, lastname, emailAddress, mobileNo, idNumber, password,
    locale, dateFormat, active, officeId
}

err.preventDefault()
try {
    let response = await fetch(myUrl, {
        // 去掉no-cors,默认就是cors模式
        method: 'POST',
        // 后端允许带凭证就用include,否则可设为same-origin或移除
        credentials: 'include',
        headers: apiHeader,
        body: JSON.stringify(clientDetails),
    });
    if (!response.ok) {
        // 手动处理非2xx状态码,方便排查错误
        const errorText = await response.text();
        console.warn('请求失败:', response.status, errorText);
        return;
    }
    let data = await response.json()
    console.warn(data)
} catch (err) {
    console.warn('请求异常:', err)
}

后端必须配置的跨域规则

要解决CORS错误,后端需要添加以下响应头配置(以常见框架为例):

  • 允许来源:Access-Control-Allow-Origin: http://localhost:3000(带凭证时不能用*)
  • 允许请求方法:Access-Control-Allow-Methods: POST, OPTIONS(OPTIONS是浏览器预请求必需的)
  • 允许自定义头:Access-Control-Allow-Headers: Authorization, Content-Type, X-Fineract-Platform-TenantId
  • 带凭证支持:Access-Control-Allow-Credentials: true(如果需要传递凭证的话)

比如Spring Boot可以用@CrossOrigin注解或全局CORS过滤器;Node.js/Express可以用cors中间件配置对应参数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:10:51