请求协助:在Fetch请求Header中添加Token解决HTTP 403 Forbidden问题
Hey there! Let's get that 403 error sorted out for you. The two key issues in your current code are related to custom headers not being sent properly and missing your authorization token. Here's how to fix it step by step:
1. Remove mode: 'no-cors'
The no-cors mode restricts browsers from sending custom headers (like your auth token) and also blocks you from reading the response. Since you're trying to send an authorization token and parse JSON from the response, this mode is working against you. Remove it entirely (or set it to cors if your backend allows cross-origin requests; if this is a same-domain request, you don't need to specify the mode at all).
2. Add Your Authorization Token to Headers
Most APIs expect auth tokens to be sent in the Authorization header, typically using the Bearer scheme. Update your Headers object to include this token. If your backend expects a different header format (like X-Auth-Token), adjust accordingly, but Authorization: Bearer <token> is the industry standard.
Modified Working Code
function getAllClients() { const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); // Add your authorization token here myHeaders.append('Authorization', 'Bearer 1234abcd'); return fetch('http://localhost:8080/clients', { method: 'GET', // Removed mode: 'no-cors' to allow custom headers and response parsing headers: myHeaders, }) .then(response => { // Check if the response is successful before parsing JSON if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.json(); }) .then((user) => { console.log(user.name); console.log(user.location); }) .catch((error) => { console.error(error); }); } getAllClients();
Additional Notes
- If your backend doesn't use the
Bearerscheme, you can adjust the header value. For example, if it expects the token directly:myHeaders.append('Authorization', '1234abcd');(just confirm with your API documentation first). - I added a check for
response.okbefore parsing JSON—this helps catch any unexpected HTTP errors early, making debugging easier.
内容的提问来源于stack exchange,提问作者peronja

