最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Axios returns 403 on API call but okhttp3 (java) works fine - Stack Overflow

matteradmin6PV0评论

I know that this question might be already answered, but I checked related questions, tried the solutions but could not get it to work. Here is the issue:

Goal Get JSON response from the following API: .json?path=en-us/unreal-engine

Problem My server (localhost) throws a 403 error.

Below you can see my code and what I already tried. I assume that it is amybe a CORS related issue but I was not able to find out more. Maybe you can help. Many thanks in advance :)

Calling the API directly via Postman with a GET request works fine.

JS Code:

const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/fetch-epic-api', async (req, res) => {
    try {

        const response = await axios.get('.json?path=en-us/unreal-engine', {
        headers: {
            'accept': 'application/json',
            'cache-control': 'max-age=0',
            'sec-fetch-site': 'cross-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
        },
        });


        res.json(response.data);
    } catch (error) {
        console.error('Fehler bei der API-Anfrage:', error);
        res.status(500).json({ error: 'Es gab einen Fehler bei der Anfrage.' });
    }
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server läuft auf http://localhost:${PORT}`);
});`

Terminal output: AxiosError: Request failed with status code 403 at settle (C:\DEV_HOME\Tools\testJs\node_modules\axios\dist\node\axios.cjs:2019:12) at BrotliDecompress.handleStreamEnd (C:\DEV_HOME\Tools\testJs\node_modules\axios\dist\node\axios.cjs:3135:11) at BrotliDecompress.emit (node:events:530:35) at endReadableNT (node:internal/streams/readable:1698:12) at process.processTicksAndRejections (node:internal/process/task_queues:90:21) at Axios.request (C:\DEV_HOME\Tools\testJs\node_modules\axios\dist\node\axios.cjs:4287:41) at process.processTicksAndRejections (node:internal/process/task_queues:105:5) at async C:\DEV_HOME\Tools\testJs\diezweite.js:12:26 { code: 'ERR_BAD_REQUEST',

When doing this in Java with okhttp3, it is working. Java Code:

public static void main(String[] args) { 

OkHttpClient client = new OkHttpClient(); 
   Request request = new Request.Builder()
            .url(".json?path=en-us/unreal-engine")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            System.err.println("Fehler bei der API-Anfrage: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();

                try {
                    JSONObject jsonObject = new JSONObject(responseBody);
                    System.out.println("Antwort von der API: ");
                    System.out.println(jsonObject.toString(2));
                } catch (Exception e) {
                    System.err.println("Fehler beim Parsen der Antwort: " + e.getMessage());
                }
            } else {
                System.err.println("Fehler bei der API-Anfrage, Statuscode: " + response.code());
            }
        }
    });
}`
Post a comment

comment list (0)

  1. No comments so far