2

I'm using express for my server side, and i'm making a post request to the server from the client, using fetch.

The data that i'm posting to the server are being sent and displayed. The data from the server's response can't be seen anywhere in the client.

Here's my code in the server side:

app.post('/info',
ensureAuthenticated, function(req,res){
   console.log(req.body)
   var tryFetch = {myString: 'I am working fetch'};

   res.setHeader('Content-Type', 'application/json');
   res.end(JSON.stringify(tryFetch));
})

The client side is as follows:

fetch("/info", {
    method: "post",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },

    body: JSON.stringify({
        name : e.target.parentElement.username,
        socketID : e.target.parentElement.socketID,
        id : e.target.parentElement.id,
    })
})
.then( (response) => { 
    console.log(response)
}); 

When i console.log() the response, the console displays:

Response {type: "basic", url: "http://localhost:4000/info", redirected: false, status: 200, ok: true, …}

type: "basic"
url: "http://localhost:4000/info"
redirected: false
status: 200
ok: truestatusText: "OK"
headers: Headers
__proto__: Headersbody: (...)
bodyUsed: false
__proto__: Response

I don't know what i'm missing here, and cannot send data from the server to the client. Can anyone help me with this please? It will be much appreciated. Thank you for your time

2
  • What happens when you try this call from Postman? Commented Apr 24, 2020 at 23:29
  • @LearningEveryday I tried this from Postman and it returns the json in the body. It also returns one cookie and 6 headers Commented Apr 25, 2020 at 0:07

3 Answers 3

4

So, i finally found out what's wrong with this case.

The problem is not on the server, but on the client and the fetch promise. Actually, what made me think that the problem was on fetch, was when i console.log(res.body) and got

ReadableStream {locked: false}
locked: false
__proto__: ReadableStream

Here's what worked for me. I replaced

.then( (response) => { 
    console.log(response)
}); 

with

.then(response => response.json())
                .then((body) => {
                     console.log(body);
                });  

So in conclusion the fetch must look like this:

fetch("/info", {
    method: "post",
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },

    //make sure to serialize your JSON body
    body: JSON.stringify({
        name : e.target.parentElement.username,
        socketID : e.target.parentElement.socketID,
        id : e.target.parentElement.id,
    })
})
.then(response => response.json())
.then((body) => {
        console.log(body);
}); 

Now the response from the server is displayed when i console.log()

Sign up to request clarification or add additional context in comments.

Comments

0

You are supposed to res.send or res.json not res.end.

res.end() is used to quickly end the response without any data.

app.post('/info',
ensureAuthenticated, function(req,res){
   console.log(req.body)
   var tryFetch = {myString: 'I am working fetch'};

   res.setHeader('Content-Type', 'application/json');
   res.send(JSON.stringify(tryFetch));
})

UPDATE

To return json

app.post('/info',
ensureAuthenticated, function(req,res){
   console.log(req.body)
   var tryFetch = {myString: 'I am working fetch'};
   res.json(tryFetch);
})

5 Comments

Unfortunately, i've also tried this and doesn't change the result. The response is still the same as i mentioned above.
@we_mor why do you have this line res.setHeader('Content-Type', 'application/json');?
because i want to return json. Do you think it's causing any problem?
@we_mor yeah, you don't need that line, if you want to return json look at my edit
This is not working either, the same thing's happening @1baga
0

Had this exact same issue using axios due to the argument I was using for .then(). The following update worked for me...

axios.post(url, userInfo)
            .then((req, res) => {
                console.log('Response:', res)
            })
            .catch(error => console.log("client Error:", error))

Instead of .then((req, res)=>{})

Updated to .then((res) => {})

axios.post(url, userInfo)
            .then((res) => {
                console.log('Response:', res)
            })
            .catch(error => console.log("client Error:", error))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.