Comments (21)
I also trying with axios or fetch and having constatly cors error.
from free-api-worldcup2022.
Which stack? With next you may use SSR
from free-api-worldcup2022.
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.
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.
You should not call the service directly. You must call the service through your own server
from free-api-worldcup2022.
@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.
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.
@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.
@vinibgoulart im using qwik
from free-api-worldcup2022.
@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 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.
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.
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.
and use a proxy from the client?
from free-api-worldcup2022.
@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.
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.
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.
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.
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.
Hello, I have made my own API with NestJs consuming @Raminmr's API, I explain it on my YouTube channel
from free-api-worldcup2022.
Thanks @ayan-de
from free-api-worldcup2022.
Related Issues (20)
- Match Morocco vs Spain HOT 1
- Incorrect teams for 12/6 Portugal vs Switzerland (API returns Portugal vs Brazil) HOT 1
- API returning 17 goals for Morocco on match not started yet (12/6 Spain vs, Morocco ) HOT 2
- Home vs away team switched for all R16 matches HOT 2
- 504 error HOT 2
- API login timeout HOT 1
- gateway down again HOT 1
- 504 Gateway Time-out HOT 3
- Wasn't able to get data for the last 14 hours HOT 3
- Match id= 638923be0eab2168b945af35 HOT 1
- Not Getting data for fixtures by date HOT 6
- server doesn't respond to ping or curl from another machine using multiple dns resolvers
- The api is no longer returning upcoming matches, all matches api is returning right now are already finished. Please update HOT 2
- Missing Goal in France vs. Australia HOT 2
- Match contains wrong scorers HOT 1
- The api is no longer returning upcoming matches, all matches api is returning right now are already finished. Please update
- Players data needed!
- Wrong score HOT 3
- Scorer arrays missing from match.
- connect ETIMEDOUT 188.121.121.178:80 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from free-api-worldcup2022.