[Vuejs]-Get API foreign key relation with Axios in VueJS

0👍

This way to get the return name with async/await pattern.

And axios needs a Accept-Encoding with correct format.

const getAuthor = async () => {
...
   const res = await axios.get(...);
   return Promise.resolve(res.data.name);
};

getAuthor()
    .then(result => {
        console.log(result);
    })

Demo code

const axios = require("axios");

const getAuthor = async () => {
    try {
        const res = await axios.get('https://jsonplaceholder.typicode.com/users/1',
            {
                headers: {
                    'Accept-Encoding': 'application/json',
                }
            }
        );
        return Promise.resolve(res.data.name);
    } catch (error) {
        return Promise.reject(error);
    }
};

getAuthor()
    .then(result => {
        console.log(result);
    })
    .catch(error => {
        console.error(error);
    });

Result this code

$ node get-data.js
Leanne Graham

This is express server version

const express = require("express")
const axios = require("axios")
const cors = require("cors")

const PORT = 3030

const app = express()
app.use(express.urlencoded({ extended: true }))
app.use(cors())

const getAuthor = async () => {
    try {
        const res = await axios.get('https://jsonplaceholder.typicode.com/users/1',
            {
                headers: {
                    'Accept-Encoding': 'application/json',
                }
            }
        );
        return Promise.resolve(res.data.name);
    } catch (error) {
        return Promise.reject(error);
    }
};

app.get("/users/:id", async (req, res) => {
    getAuthor()
        .then(result => {
            res.json(result)
        })
        .catch(error => {
            console.error(error);
        });
})

app.listen(PORT, (err) => {
    if (err)
        console.log("Error in server setup")
    console.log("Server listening on Port", PORT);
})

install dependencies

npm install express axios cors

run it

$ node data-server.js
Server listening on Port 3030

Open this URL Chrome and open DevTool by F12

http://localhost:3030/users/1

enter image description here

Leave a comment