Michael
Michael

Reputation: 1674

How do I send error message from server to client?

I'm making some requests from my express server, and I'm wondering how I can pass an error message to the client side. I want to be able to see the error message when I console log from the client as well as from the server, but I'm not sure how to relay this message back to the client to make that possible.

Here is an example of a request from my server.js file

app.get('/assign*', (request, response) => {
    var baseurl = 'https://OURACC.nocrm.io/api/v2/'
    var apikey = crmkey;

    var pathname = request.url; // retrieves the requested pathname (ie, /crm/path)
    pathname = pathname.split('?');
    pathname = pathname[0].split('/')
    var parameters = request.query.params;
    var path = pathname[2]; // gets request path for the crm

   var lead_id = parameters.lead_id
    var user_id = parameters.user_id

    var params = {
        user_id: user_id
    }

    if(path === 'leads'){

            axios.post(baseurl + path + '/' + lead_id + '/assign',
                params
            ,{
                headers: {'X-API-KEY': apikey, content_type: "json", accept: "application/json"} 
            }).then(function(res){
                response.send(res.data);
            }).catch(function(error){
                console.log("ERROR in /assign/leads/{id}/assign" + error);
            })

    }

})

This is what the call to this request looks like client side

 $.get('/assign/leads', {params: data}).then(response => {
                console.log(response);
            }).catch(error => {
                console.log(error);
            })

I've tried this server side

response.send(error)

but this doesn't return me anything client side like I was expecting.

I'm sure this is something simple, but I couldn't find much online about it, thanks.

Upvotes: 0

Views: 4080

Answers (2)

Tsepo Nkalai
Tsepo Nkalai

Reputation: 1512

If I read your code correctly, just put response.send(yourErrorMessage) in the catch block

Upvotes: 2

Denerator
Denerator

Reputation: 451

You have to specify response code. For example:

res.status(400);
res.send('None shall pass');

Upvotes: 0

Related Questions