如何在ng2-completer中添加HTTP请求头?请求头未生效排查
Hey there! I’ve run into similar header issues with ng2-completer before, so let’s break down why your authorization and content-type headers aren’t showing up in your TypeScript requests.
Common Causes & Fixes
1. You’re Using Deprecated Angular HTTP Classes
If you’re on Angular 4.3+, the old Headers and RequestOptions classes are deprecated in favor of HttpHeaders from @angular/common/http. ng2-completer is likely built to work with the newer class, so switching to HttpHeaders might fix the issue. Try updating your code like this:
import { HttpHeaders } from '@angular/common/http'; // ... // Initialize headers with the modern HttpHeaders class const headers = new HttpHeaders() .set('Content-Type', 'application/json') .set('Authorization', 'Bearer JeBVR3A'); // Set up the remote service this.dataService = completerService.remote( "https://arsapi.azurewebsites.net/api/searchusers?searchstring=", 'userName', 'userName' ); // Pass the headers in the request options this.dataService.requestOptions({ headers });
2. Request Options Might Need to Be Set Upfront
Sometimes ng2-completer caches the initial service configuration, so setting requestOptions after initializing the remote service might not register. Try restructuring your code to pass options directly when creating the service:
const headers = new HttpHeaders() .set('Content-Type', 'application/json') .set('Authorization', 'Bearer JeBVR3A'); // Create the remote service with options included from the start this.dataService = completerService.remote( "https://arsapi.azurewebsites.net/api/searchusers?searchstring=", 'userName', 'userName', { headers } // Pass options here directly );
3. Verify Backend CORS Configuration
While Postman works without restrictions, browsers enforce strict CORS rules. Make sure your backend’s Access-Control-Allow-Headers response header explicitly includes Authorization and Content-Type. If these headers aren’t whitelisted, the browser will strip them before sending the request.
4. Debug the Request in Your Browser
Open your browser’s DevTools (Network tab) to inspect the actual request:
- Check if the
AuthorizationandContent-Typeheaders appear in the request details. - Look for a failed OPTIONS pre-flight request—this is a clear sign of a CORS misconfiguration.
Final Notes
If none of the above fixes work, double-check your ng2-completer version. Older releases might have different syntax for passing request options. You can also try reinitializing the data service after setting options to ensure changes are picked up.
内容的提问来源于stack exchange,提问作者Niranjan

