Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to use it with JavaScript #57

Open
amanzew opened this issue Nov 16, 2022 · 21 comments
Open

how to use it with JavaScript #57

amanzew opened this issue Nov 16, 2022 · 21 comments

Comments

@amanzew
Copy link

amanzew commented Nov 16, 2022

i have been trying to change the cURL request to JavaScript with a fetch method however, it is not working
sample
fetch('http://api.cup2022.ir/api/v1/user/login', {method: 'POST',
headers: {
'Content-Type': 'application/json'
},body: JSON.stringify({
'email': 'XXXXXXXX.com',
'password': 'XXXXXXXXXX'
})})

@Gondrak08
Copy link

Gondrak08 commented Nov 16, 2022

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

@leoteixeiraa
Copy link

leoteixeiraa commented Nov 16, 2022

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
)
})
})
)
}

@ahocevar99
Copy link

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?

@rezarahiminia
Copy link
Owner

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

@amanzew
Copy link
Author

amanzew commented Nov 18, 2022

@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'

@vinibgoulart
Copy link

Which stack? With next you may use SSR

@notsag01
Copy link

notsag01 commented Nov 18, 2022

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,

@notsag01
Copy link

notsag01 commented Nov 18, 2022

@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'}

@amanzew
Copy link
Author

amanzew commented Nov 18, 2022

@vinibgoulart im using qwik

@vinibgoulart
Copy link

vinibgoulart commented Nov 18, 2022

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

You need to register an account before logging in

@notsag01
Copy link

notsag01 commented Nov 18, 2022

@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

@Budziol
Copy link

Budziol commented Nov 19, 2022

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

@notsag01
Copy link

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.

@masedri
Copy link

masedri commented Nov 19, 2022

and use a proxy from the client?

@aashishpanthi
Copy link

@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

@masedri
Copy link

masedri commented Nov 19, 2022

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

@Aladdin4u
Copy link

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

@amanzew
Copy link
Author

amanzew commented Nov 23, 2022

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'
}
})

@ayan-de
Copy link

ayan-de commented Nov 28, 2022

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...

@dcardonac31
Copy link

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

https://youtu.be/kc3VurqhiZw

@Aladdin4u
Copy link

Thanks @ayan-de

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests