使用Fetch API调用URL时出现net::ERR_INSECURE_RESPONSE错误求助
Hey there! Let's tackle that net::ERR_INSECURE_RESPONSE error you're hitting with your Fetch API call. First, let's break down what's going on and walk through fixes step by step.
What's Causing the net::ERR_INSECURE_RESPONSE Error?
This error means your browser doesn't trust the SSL certificate on the target server. Common reasons include:
- The certificate is self-signed (not issued by a trusted certificate authority like Let's Encrypt)
- The certificate has expired or doesn't match the server's domain
- The server's SSL certificate chain is incomplete
On top of that, there are a few issues in your Fetch code that we need to fix, plus you haven't added logic to handle the required login authentication.
Step 1: Fix the SSL Certificate Issue (Core Problem)
For Development/Testing Environments
If you're using a self-signed certificate for testing:
- Manually visit the target URL in your browser. When you see the "Not Secure" warning, click Advanced > Proceed to [domain]—this tells your browser to trust the certificate temporarily, and your Fetch calls will start working.
- If you need to bypass SSL checks entirely for local testing (only do this for development, never production), launch your browser with a specific flag:
# Windows (Chrome) chrome.exe --ignore-certificate-errors # Mac (Chrome) open -a "Google Chrome" --args --ignore-certificate-errors
For Production Environments
- Verify your SSL certificate is valid, hasn't expired, and matches your server's domain. Use an SSL testing tool to check for certificate chain issues.
- Ensure you're using a certificate issued by a trusted CA (Let's Encrypt offers free, valid certificates).
Step 2: Fix Your Fetch Code
Your current code has a couple of critical mistakes, plus missing authentication logic. Here's how to fix it:
First, Correct the Code Syntax Issues
Access-Control-Allow-Originis a response header—you don't need to set it in your request. Browsers handle cross-origin request headers automatically, so remove this line.- You wrote
header: headerin yoursentDataobject, but it should beheaders: headers(plural) — this typo was preventing your custom headers from being sent.
Add Authentication Logic
Since you need to log in to access the content, here are two common scenarios:
Scenario 1: Server Uses HTTP Basic Auth
If the server expects basic username/password authentication, encode your credentials and add them to the Authorization header:
const username = "***"; const password = "***"; const url = "***"; // Correct headers setup const headers = new Headers({ 'Content-Type': 'multipart/form-data', // Encode credentials for Basic Auth 'Authorization': 'Basic ' + btoa(`${username}:${password}`) }); const sentData = { method: 'POST', mode: 'cors', headers: headers, // Fixed plural spelling // Build your form data if needed body: new FormData() }; return new Promise((resolve, reject) => { fetch(url, sentData) .then(response => { if (!response.ok) { throw new Error(`HTTP Error! Status: ${response.status}`); } return response.json(); // Adjust to response.text() if needed }) .then(data => resolve(data)) .catch(error => reject(error)); });
Scenario 2: Server Requires a Login Token
If you need to first call a login endpoint to get an auth token, then use that token for subsequent requests:
const username = "***"; const password = "***"; const loginUrl = "***"; // Your login endpoint const contentUrl = "***"; // The URL you want to access after login // First, log in to get a token fetch(loginUrl, { method: 'POST', headers: new Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ username, password }) }) .then(response => response.json()) .then(loginResponse => { const authToken = loginResponse.token; // Adjust based on your server's response // Now use the token to access the protected content return fetch(contentUrl, { method: 'POST', mode: 'cors', headers: new Headers({ 'Content-Type': 'multipart/form-data', 'Authorization': `Bearer ${authToken}` }), body: new FormData() }); }) .then(response => response.json()) .then(contentData => console.log(contentData)) .catch(error => console.error("Request failed:", error));
Extra Tips
- Avoid hardcoding usernames and passwords in frontend code—it's a huge security risk. In production, use a backend proxy to handle authentication.
- If you're not uploading files, consider using
application/jsoninstead ofmultipart/form-data—it's simpler and less prone to errors. - Double-check that the target server's CORS configuration allows your frontend domain (look for
Access-Control-Allow-Originin the server's response headers).
内容的提问来源于stack exchange,提问作者ANISHA

