Angular 5应用遇CSP错误:资源加载与Function()调用被阻止
Alright, let's tackle these two CSP errors you're hitting in your Angular 5 app—they're common when working with strict content security policies, especially with Angular's JIT compiler behavior.
1. "Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src”)
What's happening
The default-src directive in CSP acts as a fallback for all resource types (scripts, styles, images, etc.) that don't have their own explicit directive. If you're seeing this error, it means a resource (like a script, style sheet, or image) is trying to load from self (your app's origin), but either:
- Your
default-srcdoesn't include'self', or - You haven't defined a specific directive for that resource type (e.g.,
script-src,style-src) and the fallbackdefault-srcis too restrictive.
How to fix it
Update your CSP to explicitly allow the necessary resource types from self. For example, if you're using a meta tag to set CSP, adjust it to include specific directives:
<meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; ">
style-srcneeds'unsafe-inline'in Angular 5 because the framework uses inline styles for component styling (this is safe in most cases, and Angular mitigates risks here).- Add other directives (like
connect-srcif you're making API calls) as needed for your app.
2. "call to Function() blocked by CSP" (with JitCompiler in the stack trace)
What's happening
Angular 5 uses JIT (Just-in-Time) compilation by default in development mode. JIT compiles your components and templates at runtime, which relies on dynamic code generation via Function() and eval()—both of which are blocked by strict CSP rules that don't include 'unsafe-eval'.
How to fix it
You have two options depending on your environment:
For Development Environment
If you need to keep using JIT for development, add 'unsafe-eval' to your script-src directive in CSP:
<meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; ">
This allows the JIT compiler to do its work while keeping other resources restricted.
For Production Environment
For production, you should use AOT (Ahead-of-Time) compilation instead. AOT compiles your app during the build process, eliminating the need for runtime code generation. This means you can keep a strict CSP without 'unsafe-eval'.
To enable AOT in Angular 5, run your build with the --prod flag:
ng build --prod
The production build automatically enables AOT, so your compiled app won't rely on Function() or eval() at runtime. Your production CSP can then be strict:
<meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; ">
内容的提问来源于stack exchange,提问作者Manu Chadha

