Home > Software engineering >  Why fetch method can't fetch anything?(feat node.js, restAPI)
Why fetch method can't fetch anything?(feat node.js, restAPI)

Time:05-31

I'm a newbie in node.js and mySQL I do clone coding restaurant site. So I made databases and I make server.


var app=express();


app.listen(9999,function(){ //I'm using 9999 port and I use Localhost
    console.log('Server is running');
})

//connect mySQL
var client=mysql.createConnection({
    user:'root',
    password:'pswd' //for Question
});

I use 9999 port and I open my server on localhost.

and I have html. It's just test html file(minuk_test.html) and when I request to ''/store/restaurant_info', I want to recieve data by using json.

-- main.js --

app.get('/store/restaurant_info',function(request,response){
    client.query('SELECT * FROM RESTAURANT_INFO',function(error,result,fields){
        if(error){
            console.log('Query syntax error');
        }else{
            response.json(result);
            console.dir(result[0].name);
            console.log('check sending data');
        }
    });
});

app.get('/Project/html/minuk_test.html',function(request,response){
    fs.readFile('../html/minuk_test.html','utf-8',function(error,data){
        if(error){
            console.log('Loading minuk_test.html is failed');
        }
        response.send(data);
    })
})

and it's my html code. -- html file--

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API TEST</title>
    <link rel="stylesheet" href="/minuks_test.js">
</head>
<body>
    <h1>Test</h1>
    <div id="restaurant">
        <span></span>
        <span></span>
    </div>
</body>
</html>

and it's my javascript

--javscript file--

import fetch from "node-fetch";

function getAPI(){
    const url=`http://127.0.0.1:9999/store/restaurant_info`;
    fetch(url)
        .then(response=>{
            console.log(response);
            response.json();
        })
        .then(data={
            console.log(data);
        });
}

getAPI();

I expect when I enter "minuk_test.html", html execute javascript file. In javascript file, request to url buy using get.

but I have two problem.

first, I run my server. and enter localhost:9999/Project/html/minuk_test.html if html run javascript file. and javascript file request to /store/restaurant_info. then server console print result[0].name and 'check sending data' but console is clear.

Second, I run javascript file with server turned on. then console.log(response) is here

Response {
  size: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    stream: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    boundary: null,
    disturbed: false,
    error: null
  },
    type: 'default',
    url: 'http://127.0.0.1:9999/store/restaurant_info',
    status: 200,
    statusText: 'OK',
    headers: {
      connection: 'close',
      'content-length': '8035',
      'content-type': 'application/json; charset=utf-8',
      date: 'Mon, 30 May 2022 11:53:15 GMT',
      etag: 'W/"1f63-IYBGYq/MlY5TBn49Gp7cFQ7aH A"',
      'x-powered-by': 'Express'
    },
    counter: 0,
    highWaterMark: 16384
  }
}

undefined //console.log(data);

response.size is 0. is it normal? and console.log(data) is undefined

but in postman, enter image description here

postman can recieve json data.

I can't understand why my html can't receive json. Please help me.

CodePudding user response:

because there's no javascript file included in the html file, and it's not included because you're not serving static files on the web server, so nothing runs (also, it's not stylesheet, but script tag)

it should work if you inline javascript. Also, in the browser you use fetch, and node-fetch on the server-side):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API TEST</title>
    <script>
        function getAPI(){
            const url=`http://127.0.0.1:9999/store/restaurant_info`;
            fetch(url)
                .then(response=>{
                    console.log(response);
                    response.json();
                })
                .then(data={
                    console.log(data);
                });
        }

        getAPI();        
    </script>
</head>
<body>
    <h1>Test</h1>
    <div id="restaurant">
        <span></span>
        <span></span>
    </div>
</body>
</html>

but you should setup static files, see here:

https://expressjs.com/en/starter/static-files.html

Also, you can setup your own route, without extension, and also you can use .sendFile to serve specific file instead of fs, but you need to provide absolute path (via path module):

see here:

http://expressjs.com/en/api.html#res.sendFile

app.get('/my-route', function(request, response, next) {

    response.sendFile(require('path').join(__dirname, '../html/minuk_test.html'), function(err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    });
});
  • Related