简体   繁体   中英

NodeJS Express app.get() not responding to call

I'm new to nodejs, and i wanted to make something like a weather app. I have file pass.txt with my api key, and i want to read this file, and then wait for get calls at api endpoint, but the app.get is behaving like there was no get call for him. after clicking the button it's console logging out my html code. What can i do to get the api key instead of html code?

JS CODE

const btn = document.querySelector('#btn')

    btn.addEventListener('click', e =>{
        
        fetch('/api')
        .then(res => res.text())
        .then(data =>{
            console.log(data)
        })

    })

nodejs

const http = require('http')
const express = require('express')
const app = express();
const fs = require('fs')


let port = 2932;

console.log('listening on' + port)

const key = fs.readFile('./public/pass.txt', 'utf8', (err,data) =>{
    if (err) console.log(err)

    app.get('/api', (req,res) =>{
        console.log(key)
        res.send(data)
    })

    console.log(data) // console logs the key
})


http.createServer((req,res) =>{
    res.writeHead(200, {'Content-type': 'text/html'})
    fs.readFile('public/index.html', (error,data) =>{
        if(error){
            res.writeHead(404)
            res.write('Files not found')
        }

        res.write(data)
        res.end()
    })
}).listen(port)

You are registering the route handler inside the readFile callback, while you most likely need to do the opposite. Also there is no need to use the low level http interface to setup a server taking into account that you have express :

const express = require('express')
const app = express();
const fs = require('fs')
const path = require('path');

app.get('/api', (req,res) =>{
  fs.readFile('./public/pass.txt', 'utf8', (err,data) =>{
    if (err) console.log(err)
    res.send(data)
  })
})

app.use('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'views/index.html'));
})

let port = 2932;

app.listen(port, () => {
  console.log('listening on ' + port)
})

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