Coder Social home page Coder Social logo

Comments (21)

Gondrak08 avatar Gondrak08 commented on August 16, 2024 2

I also trying with axios or fetch and having constatly cors error.

from free-api-worldcup2022.

vinibgoulart avatar vinibgoulart commented on August 16, 2024 1

Which stack? With next you may use SSR

from free-api-worldcup2022.

leoteixeiraa avatar leoteixeiraa commented on August 16, 2024

I too am having the same problem! If someone manages to solve it, could you post the solution here?

Here is my code in TypeScript:

I too am having the same problem! If someone manages to solve it, could you post the solution here?

Here is my code in TypeScript:

public header = {
headers: new HttpHeaders()
.set("Authorization", "Bearer ")
.set("Content-Type", "application/json")
}
public httpOptions = {
headers: new HttpHeaders({'Authorization': ' ' , 'Content-Type': 'application/json'})
};
get apiListAllPlayer(): Observable {
return this.http.get(this.url, this.httpOptions).pipe(
tap(res => res),
tap(res => {
res.results?.map((resPlayer: any) => {
this.apiGetProducts(resPlayer.url).subscribe(
res => resPlayer = res
)
})
})
)
}

from free-api-worldcup2022.

ahocevar99 avatar ahocevar99 commented on August 16, 2024

Same problem here. Got the response in Rest Client in VScode when calling it from a .http file, but then when trying to do the same thing with javascript - the problem with cors appeared.
Is it possible to get data from the REST Client response?

from free-api-worldcup2022.

rezarahiminia avatar rezarahiminia commented on August 16, 2024

You should not call the service directly. You must call the service through your own server

from free-api-worldcup2022.

amanzew avatar amanzew commented on August 16, 2024

@Raminmr how can i achieve that, let's say I'm running my server on http://localhost:3000
what should i call instead of 'http://api.cup2022.ir/api/v1/user/login'

from free-api-worldcup2022.

notsag01 avatar notsag01 commented on August 16, 2024

El mismo problema aqui. Obtuve la respuesta en Rest Client en VScode cuando lo llamé desde un archivo .http, pero luego, cuando intenté hacer lo mismo con javascript, apareció el problema con cors. ¿Es posible obtener datos de la respuesta del cliente REST?

const otrosParametros={
Headers:{
"Content-Type": "application/json",
'Access-Control-Allow-Origin': 'http://127.0.0.1:5500/'
},
body:Data,
method: "POST"
}

You should add this in the header,

from free-api-worldcup2022.

notsag01 avatar notsag01 commented on August 16, 2024

@vinibgoulart , regarding the password, I must create one? What password should I send? I have an error message:

{status: 'error', message: 'User validation failed: password: Please provide y…rovide your email, name: Please provide your name'}

from free-api-worldcup2022.

amanzew avatar amanzew commented on August 16, 2024

@vinibgoulart im using qwik

from free-api-worldcup2022.

vinibgoulart avatar vinibgoulart commented on August 16, 2024

@notsag01 You already register? https://github.com/raminmr/free-api-worldcup2022#register

You need to register an account before logging in

from free-api-worldcup2022.

notsag01 avatar notsag01 commented on August 16, 2024

@notsag01 You already register? https://github.com/raminmr/free-api-worldcup2022#register

You need to register an account before logging in

@vinibgoulart , It won't let me register, it returns "error 400". Thanks all the same

from free-api-worldcup2022.

Budziol avatar Budziol commented on August 16, 2024

Hi guys i managed to do this.
First of all you need to set up a server, here is the link how to do this https://dev.to/pratham10/how-to-set-up-a-node-js-express-server-for-react-2fja
Next if your app and server are connected you need to import axios to your server, just install it in your server folder using npm i axios and import like this in server index.js: const axios = require("axios");

const axios = require('axios');

//u dont need to keep register bcs your using it only once, so make a call and get rid of that
app.get("/api/register", (req, res) => {
const data = JSON.stringify({
name: "userName",
email: "userEmail",
password: "8CharPwd",
passwordConfirm: "userPwdConfirm",
});

const config = {
method: "post",
url: "http://api.cup2022.ir/api/v1/user",
headers: {
"Content-Type": "application/json",
},
data: data,
};

axios(config)
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});

//next you need to login to get token. You need to call this endpoint 1/24h(bcs every time you are logging in your token changes, your being loggedIn for 24hrs) and store token in some variable.
app.get("/api/login", (req, res) => {
const data = JSON.stringify({
email: "userEmail",
password: "8CharPwd",
});

const config = {
method: "post",
url: "http://api.cup2022.ir/api/v1/user/login",
headers: {
"Content-Type": "application/json",
},
data: data,
};

axios(config)
.then(function (response) {
token = response.data.data.token;
})
.catch(function (error) {
console.log(error);
});
});

//teams
app.get("/api/teams", (req, res) => {

const config = {
method: "get",
url: "http://api.cup2022.ir/api/v1/team",
headers: {
Authorization: Bearer ${token},
"Content-Type": "application/json",
},
};

axios(config)
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});

from free-api-worldcup2022.

notsag01 avatar notsag01 commented on August 16, 2024

Bud

Hola chicos logré hacer esto. En primer lugar, debe configurar un servidor. Aquí está el enlace sobre cómo hacerlo https://dev.to/pratham10/how-to-set-up-a-node-js-express-server-for-react -2fja A continuación, si su aplicación y el servidor están conectados, necesita importar axios a su servidor, simplemente instálelo en la carpeta de su servidor usando npm i axios e impórtelo así en el servidor index.js: const axios = require("axios");

const ejes = require('ejes');

// no necesita mantener el registro porque lo está usando solo una vez, así que haga una llamada y deshágase de esa aplicación.get("/api/register", (req, res) => { const data = JSON.stringify( { nombre: "userName", correo electrónico: "userEmail", contraseña: "8CharPwd", passwordConfirm: "userPwdConfirm", });

const config = { método: "publicación", url: " http://api.cup2022.ir/api/v1/user ", encabezados: { "Tipo de contenido": "aplicación/json", }, datos: datos , };

axios(config) .then(función (respuesta) { res.send(JSON.stringify(respuesta.datos)); }) .catch(función (error) { console.log(error); }); });

//a continuación, debe iniciar sesión para obtener el token. Debe llamar a este punto final 1/24 h (bcs cada vez que inicie sesión en sus cambios de token, estará conectado durante 24 horas) y almacenará el token en alguna variable. app.get("/api/login", (req, res) => { const data = JSON.stringify({ email: "userEmail", contraseña: "8CharPwd", });

const config = { método: "publicación", url: " http://api.cup2022.ir/api/v1/user/login ", encabezados: { "Tipo de contenido": "aplicación/json", }, datos : datos, };

axios(config) .then(función (respuesta) { token = respuesta.datos.datos.token; }) .catch(función (error) { console.log(error); }); });

//equipos app.get("/api/equipos", (req, res) => {

const config = { método: "get", url: " http://api.cup2022.ir/api/v1/team ", encabezados: { Autorización: Bearer ${token}, "Content-Type": "application/json", }, };

axios(config) .then(función (respuesta) { res.send(JSON.stringify(respuesta.datos)); }) .catch(función (error) { console.log(error); }); });

Thank you for taking the time to give such a detailed explanation. I'll try it tomorrow.

from free-api-worldcup2022.

masedri avatar masedri commented on August 16, 2024

and use a proxy from the client?

from free-api-worldcup2022.

aashishpanthi avatar aashishpanthi commented on August 16, 2024

@Raminmr how can i achieve that, let's say I'm running my server on http://localhost:3000 what should i call instead of 'http://api.cup2022.ir/api/v1/user/login'

Looks like you are calling API directly from the client side using React. If you also have a nodejs server running, call the football API from there.

If you don't have your own server then create one with express. Create your own API endpoint and call the endpoint from there so that your express server further calls the football API. Basically, you are creating a proxy server.

The CORS error will be resolved this way

from free-api-worldcup2022.

masedri avatar masedri commented on August 16, 2024

Solved for vite

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3000,
    proxy: {
      "/api": {
        target: "http://api.cup2022.ir/api/v1/",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
      cors: false,
    },
  },
  plugins: [vue()],
});

from free-api-worldcup2022.

Aladdin4u avatar Aladdin4u commented on August 16, 2024

Solved for vite

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3000,
    proxy: {
      "/api": {
        target: "http://api.cup2022.ir/api/v1/",
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ""),
      },
      cors: false,
    },
  },
  plugins: [vue()],
});

Which folder will this code be

from free-api-worldcup2022.

amanzew avatar amanzew commented on August 16, 2024

thanks everyone for your help, this is the code that worked for me on Vite server

on vite.config.ts file
server: {
port: 3000,
proxy: {
"/api": {
target: "http://api.cup2022.ir",
changeOrigin: true,
secure: false,
cors: false,
rewrite: (path) => path.replace(/^/api/, "http://api.cup2022.ir/api"),
}, },},
in order to fetch
for example Standing end point
fetch('api/v1/standings', headers: {
'Authorization': XXXXXX
'Content-Type': 'application/json'
}
})

from free-api-worldcup2022.

ayan-de avatar ayan-de commented on August 16, 2024

wait! u cannot directly use it with javascript because as the author states that we can fetch the API on "SERVER SIDE" only for that u can use popular javascript framework "NODE js" here how i solved ..

=> app.js (my server file)

      const express = require('express')
      const app = express()
      const path = require("path")
      const port = process.env.PORT || 3000
      var bodyParser = require('body-parser')
     
      const { response } = require('express');
      
      app.use(express.static('public'));
      
      app.get('/football', async(req, res) => {
      
        const options = {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer YOUR TOKEN HERE',
            'Content-Type': 'application/json'
          }
        };
      
        const api_url = `http://api.cup2022.ir/api/v1/standings/`;
        const fetch_response = await fetch(api_url, options);
        const json = await fetch_response.json();
        res.json(json);
        })
      
      app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
      })

=> in javascript file

    const api_url = `/football`;
    const response = fetch(api_url);
    const json = response.json();
    console.log(json);

THATS IT AND NOW U WILL GET OUTPUT IN THE CONSOLE...

from free-api-worldcup2022.

dcardonac31 avatar dcardonac31 commented on August 16, 2024

Hello, I have made my own API with NestJs consuming @Raminmr's API, I explain it on my YouTube channel

https://youtu.be/kc3VurqhiZw

from free-api-worldcup2022.

Aladdin4u avatar Aladdin4u commented on August 16, 2024

Thanks @ayan-de

from free-api-worldcup2022.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.