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

Angular 2项目XMLHttpRequest请求现有文件仅index.html返回200其余404求助

Fixing 404 Errors for Non-index.html Files in Angular 2 XMLHttpRequest Calls

Hey there! I’ve run into this exact issue before with Angular projects, so let’s walk through why this is happening and how to get your files loading correctly.

Why Only index.html Works?

  • Angular is a single-page application (SPA) by default. Its routing system is set up to redirect most unknown requests to index.html—that’s why you get a 200 for it even if the path seems off.
  • Non-index files like file1.html or file2.ts aren’t automatically included in your build output unless you explicitly tell Angular to treat them as static assets. The CLI only bundles files in configured directories (like src/assets) and core app files by default.
  • Also, .ts files are compiled to JavaScript during the build process—they won’t exist as separate files in your dist folder, so requesting them directly will always return 404.

Step-by-Step Fixes

  1. Add Files/Directories to Angular’s Asset Configuration
    Open your angular.json file and look for the assets array under your project’s build options. Add the path to your target directory or individual files here:

    "projects": {
      "your-project-name": {
        "architect": {
          "build": {
            "options": {
              "assets": [
                "src/favicon.ico",
                "src/assets",
                "src/your-target-directory", // Add your entire directory here
                "src/file1.html" // Or individual files if needed
              ]
            }
          }
        }
      }
    }
    

    After making this change, restart your development server (ng serve) or rebuild your project (ng build) so the new assets are included in the output.

  2. Avoid Requesting .ts Files Directly
    Since TypeScript files are compiled to JS, you can’t access them via HTTP requests. If you need to use content from file2.ts, import it directly into your component or service instead:

    import { someFunction } from './path/to/file2.ts';
    
  3. Verify Your Request Paths
    Double-check that the file variable in your XMLHttpRequest uses the correct relative path. For example, if file1.html ends up in the root of your dist folder, the path should be "file1.html"—not a path relative to your source files.

  4. Check for Routing Conflicts
    If you have custom routes set up, make sure none of them are accidentally matching your file paths. Angular’s router will try to handle the request first before falling back to static assets.

Once you’ve made these changes, your XMLHttpRequest calls to file1.html (and other configured assets) should return 200 as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:19:38