简体   繁体   中英

Node (Express) doesn't start

I was trying out Express and trying to learn it, and I tried to start a server, but nothing's happening. I'm trying to access 127.0.0.1:8080 through Express, and I copied ALMOST all of the example (but not all). This is my code:

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => function() {
    let ip = req.ip
    console.log(ip);

    res.send('Hello World')
})

app.listen(port, ()=>console.log(`Server started on port ${port}`))

The app will log after starting node server.js , but nothing will appear at 127.0.0.1:8080. Is there something wrong with my code?

You have an error using arrow functions, try the following:

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => {
    let ip = req.ip
    console.log(ip);

    res.send('Hello World')
})

app.listen(port, ()=>console.log(`Server started on port ${port}`))

You have made a mistake in your endpoint callback function. function keyword is not used when arrow function syntax is used.

Either you use function() {} , or you use () => {} to write functions.

Correct code snippet would be:

const express = require('express')
const app = express()
const port = 8080

app.get('/', (req, res) => {
    let ip = req.ip
    console.log(ip);

    res.send('Hello World')
})

app.listen(port, ()=>console.log(`Server started on port ${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