Bruno Gurgel
Bruno Gurgel

Reputation: 53

GET/POST methods on Express

I am configuring a server using express.

My question has nothing to do with the project itself because it is running great.

I just have a minor doubt about why I have to use GET when for me it makes more sense to use POST.

So, for short I am configuring an API key on the server side and fetching it on the client side so I can use it.

This is the snippet on the server side:

const apiKey = process.env.API_KEY;
console.log(`Your API key is ${apiKey}`);
const dataObject ={};

app.get('/api', (req,res) => {
    res.send({key: apiKey})
})

app.get('/all', sendData = (req,res) => {
    res.send(dataObject)
})

app.post('/addText', (req,res)  => {
    let newEntry = {
        agreement = req.body.agreement,
        subjectivity = req.body.subjectivity
    }

    dataObject = newEntry;
    res.send(dataObject);
} )

And then on the client side I fetch on the '/api' path:

const getApiKey = async () => {
        // Getting API key from server
        const request = await fetch('/api');
        try {
            const data = await request.json();
            console.log(data);
            return data;
        }catch(error) {
            console.log('ERROR', error);
        }
    }

Ok, that's working and everything, but my question is:

Sorry if it seems a stupid question but I am having a hard time understanding the GET method.

Thanks!

Upvotes: 0

Views: 47

Answers (3)

Chris
Chris

Reputation: 1230

Usually, you use the GET method when the client has to read some data from the server, in this case, you want to read the API_KEY defined in the server. GET has no body, but every request may be parametric by passing parameters in the query string.
On the other hand, when you have to update or create an entity on the server, that's when POST (or PUT) enters into action. Here you pass your data in the body of the request.

Upvotes: 0

Thomas Sablik
Thomas Sablik

Reputation: 16454

You are not sending any API key to the server. The server is sending the API key to the client as a response. The client uses a GET request to get the API key from /api. The names of the methods (GET, POST, PUT, DELETE, ...) are from the perspective of the client.

"And then on the client side I fetch on the '/api' path:" No. First the client sends the request with

const request = await fetch('/api');
try {
    const data = await request.json();
    console.log(data);
    return data;
}catch(error) {
    console.log('ERROR', error);
}

This triggers the callback in

app.get('/api', (req,res) => {
    res.send({key: apiKey})
})

and the server sends the response.

Upvotes: 2

Shell Code
Shell Code

Reputation: 692

This code returns the API key from the server. It does not send it from the client to the server.

app.get('/api', (req,res) => {
    res.send({key: apiKey})
}

The

res.send()

Function is constructing the response returned by the server to the client.

Upvotes: 0

Related Questions