简体   繁体   中英

Express server not sending response to client (using fetch)

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM