你說:
When I use get method of fetch api in the browser, I get the following error, "Missing required request header. Must specify one of: origin,x-requested-with". How should I adjust my code?
ChatGPT 說:

The error you're encountering suggests that the server you're making a request to requires specific headers, such as Origin or X-Requested-With, to be present in the request. This is typically a security measure to prevent certain types of attacks (e.g., Cross-Origin Resource Sharing issues).

To resolve this, you can manually add these headers to your fetch request. Here's an example of how to do this:

Example Code:

javascript
fetch('https://example.com/api', { method: 'GET', // or 'POST' depending on your request headers: { 'Origin': 'https://yourdomain.com', // Replace with your domain 'X-Requested-With': 'XMLHttpRequest' // Standard header for AJAX requests } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

Explanation:

  1. Origin Header: This header tells the server where the request originated from. You should replace 'https://yourdomain.com' with the actual domain that is making the request. If you're making the request from the same domain, it could also be window.location.origin.

  2. X-Requested-With: This header is commonly used in AJAX requests and is a way for the server to recognize that the request was made via JavaScript (typically in a client-side environment).

Why This Works:

These headers are often used to distinguish between normal browser requests and programmatic requests (like AJAX). If the server is expecting these headers, adding them should resolve the error.

Additional Consideration:

If you're working with cross-origin requests, ensure that the server you're making the request to supports CORS (Cross-Origin Resource Sharing) and is configured to accept requests from your origin.

Let me know if that helps or if you need further assistance!


ChatGPT 可能會發生錯誤。請查核重要資訊。