Angular 2项目XMLHttpRequest请求现有文件仅index.html返回200其余404求助
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.htmlorfile2.tsaren’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 (likesrc/assets) and core app files by default. - Also,
.tsfiles 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
Add Files/Directories to Angular’s Asset Configuration
Open yourangular.jsonfile and look for theassetsarray under your project’sbuildoptions. 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.Avoid Requesting
.tsFiles Directly
Since TypeScript files are compiled to JS, you can’t access them via HTTP requests. If you need to use content fromfile2.ts, import it directly into your component or service instead:import { someFunction } from './path/to/file2.ts';Verify Your Request Paths
Double-check that thefilevariable in your XMLHttpRequest uses the correct relative path. For example, iffile1.htmlends up in the root of yourdistfolder, the path should be"file1.html"—not a path relative to your source files.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

