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

Fetch API调用后未进入.then()执行,后端返回正常JSON问题

问题:前端Fetch请求调用后端接口后无法进入.then()回调

环境信息

  • Node.js 18.13.0
  • Vue-cli 5.0.8
  • 前后端分离架构:前端采用JS+Vue,后端基于Spring Boot(使用H2临时数据库),前后端在不同端口同时运行

问题现象

前端发起Fetch请求调用后端/register接口后,无法进入后续的.then()回调。前端调试时console.log("test1")、console.log("test2")均无输出,浏览器控制台也无错误信息,怀疑请求卡在.then(data => {...})环节,不确定是响应耗时过长还是其他原因。

前端代码

const userData = {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(user)
      }

const emailRequestOptions = {
        method: 'GET',
        redirect: 'follow'
      }

fetch('http://localhost:8080/register', userData)
  .then(response => response.json())
  .then(data => {

    console.log("test1")

    if (data.ok) {

      console.log("test2")
      
      fetch('http://localhost:8080/userEmail/' + this.email, emailRequestOptions)
        .then(response2 => response2.json())
        .then(data2 => this.navigateToRegistrationQuestions(data2))
        .catch(error => {
          console.error('error:', error)
        })

    } else {

      console.log('User could not be created, try again')
    }
  })
  .catch(error => {
    console.error('error:', error)
  })

后端接口代码

@PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(@RequestBody RegisterRequest request){

    return ResponseEntity.ok(service.register(request));
}


@GetMapping("/userEmail/{email}")
public ResponseEntity<Map<String, Long>> getUserIdByEmail(@PathVariable String email) { 
    return ResponseEntity.ok(uService.getUserIdByEmail(email));
}

测试情况

通过Postman测试后端/register接口,返回预期JSON:{"token": "eyJhbGciOiJIUzI1NiJo"},接口功能正常。


排查与解决建议

  1. 优先排查跨域问题
    前后端不同端口运行,大概率存在跨域拦截。浏览器会先发送OPTIONS预检请求,如果后端未配置跨域支持,Fetch请求会被静默拦截,部分浏览器不会在控制台显示明显错误,但会在「网络」面板标记请求失败。

    • 解决方式:在Spring Boot后端添加跨域配置,比如给接口添加@CrossOrigin注解,或者配置全局跨域过滤器。
  2. 修正Fetch响应处理逻辑

    • Fetch的特性是:只要服务器返回了响应(哪怕是4xx/5xx状态码),不会直接触发catch,而是进入第一个.then。你当前直接调用response.json(),如果响应格式不是合法JSON,会抛出异常但可能被后续逻辑吞掉。
    • 建议先在第一个.then里打印响应状态和原始内容,排查问题:
      .then(response => {
        console.log('响应状态码:', response.status);
        console.log('响应是否正常:', response.ok);
        return response.json();
      })
      
    • 另外,Postman返回的响应里没有ok字段,你后续判断data.ok的逻辑本身就不成立,但如果连test1都没打印,说明前面的响应解析或请求环节已经出问题了。
  3. 检查网络请求状态
    打开浏览器开发者工具的「网络」面板,查看/register请求的状态:

    • 如果请求状态是pending:可能是后端接口阻塞,或者跨域预检请求失败;
    • 如果是200但响应内容异常:检查是否是JSON格式错误;
    • 如果是4xx/5xx:需要手动通过response.ok判断是否成功,再处理错误。
  4. 关于响应耗时的可能性
    H2数据库的操作通常不会导致过长耗时,这个可能性较低,优先排查前面的跨域和响应处理逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:23:25