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

使用Angular从JSON Server获取数据时遭遇HttpErrorResponse错误求助

问题诊断与解决方案

从你提供的代码和报错情况来看,核心问题是跨域资源共享(CORS)限制——Angular项目默认运行在localhost:4200,JSON Server在localhost:3000,属于不同端口,浏览器出于安全策略会拦截这类跨域请求。


你的服务代码:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class RestapiService {
  constructor(private http: HttpClient) {}

  getTasks() {
    return this.http.get('http://localhost:3000/tasks');
  }
}

你的组件代码:

import { Component, OnInit } from '@angular/core';
import { RestapiService } from 'src/app/services/restapi.service';

@Component({
  selector: 'app-taskdisplay',
  templateUrl: './taskdisplay.component.html',
  styleUrls: ['./taskdisplay.component.css'],
})
export class TaskdisplayComponent implements OnInit {
  constructor(private service: RestapiService) {}

  ngOnInit(): void {
    this.getallTasks();
  }

  userTasks: any = [];

  getallTasks() {
    this.service.getTasks().subscribe((result) => {
      this.userTasks = result;
      console.log(this.userTasks);
    });
  }
}

两种解决方式:

方式一:给JSON Server开启CORS支持

  1. 安装cors依赖:
npm install cors --save
  1. 在JSON Server目录创建server.js文件:
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(cors());
server.use(middlewares);
server.use(router);
server.listen(3000, () => {
  console.log('JSON Server 已开启CORS,运行中');
});
  1. 修改package.json的启动脚本:
"scripts": {
  "start": "node server.js"
}
  1. 重启JSON Server,再运行Angular项目即可。

方式二:使用Angular代理配置(无需修改JSON Server)

  1. 在Angular项目根目录创建proxy.conf.json:
{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "pathRewrite": {"^/api": ""}
  }
}
  1. 修改RestapiService的请求地址:
getTasks() {
  return this.http.get('/api/tasks');
}
  1. 用代理启动Angular:
ng serve --proxy-config proxy.conf.json

这样就能正常获取JSON Server的数据并在控制台打印了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:59:19