Response.header error in node server

2019-08-23 10:38发布

I have a simple node server.

When I type 'localhost:9015' in my browser I get the error showing below.

I have checked the code and I found no error.

What am I doing wrong?

server is listening on 9015
/
C:\nodeapp\cloudnh_v2\teste.js:41
   response.header("Access-Control-Allow-Origin", "*");
            ^

TypeError: response.header is not a function
    at Server.requestHandler (C:\nodeapp\cloudnh_v2\teste.js:41:13)
    at emitTwo (events.js:125:13)
    at Server.emit (events.js:213:7)
    at parserOnIncoming (_http_server.js:602:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
[nodemon] app crashed - waiting for file changes before starting...

Code:

const http = require('http')
const port = 9015

const requestHandler = (request, response) => {
   console.log(request.url)
   response.header("Access-Control-Allow-Origin", "*");
   response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   response.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
   response.header("Cache-Control", "no-cache");

  response.end('Hello Node.js Server!')
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

0条回答
登录 后发表回答