admin管理员组

文章数量:1023744

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());
            }
        }
    });
}`

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());
            }
        }
    });
}`

本文标签: javascriptAxios returns 403 on API call but okhttp3 (java) works fineStack Overflow