你說:
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?
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:
javascriptfetch('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));
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
.
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).
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.
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!