我正在尝试访问以json形式接收到的主体中的数据,但未定义

时间:2019-10-12 03:50:19

标签: node.js

commandline:
curl -d '{number:"1009732533765201",once:1009732533765201}' -X POST  http://localhost:3000

code:
const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      l = data.body
      console.log('Partial body: ' + body, l)
    })
    request.on('end', function() {
      l = body
      console.log('Body: ' + body, l, l.number)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

console log shows l.number as undefined:
POST
Partial body: {number:"1009732533765201"} undefined
Body: {number:"1009732533765201"} {number:"1009732533765201"} undefined

l =正文正在记录为未定义。我想将主体分配给变量,以便我可以将其作为json对象使用,因此我可以执行l.number之类的操作,并具有编号,以便可以处理发布数据。我在这里想念什么吗?我正在从python转到json,因此我是新手,正在寻求帮助,以便可以将身体数据作为json对象访问,以便可以使用它。谢谢

回答:我必须使用JSON.parse。这可行。有效的新代码是:


const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      l = JSON.parse(body)
      console.log('Partial body: ' + body, l)
    })
    request.on('end', function() {
      l = JSON.parse(body)
      console.log('Body: ' + body, l, l.number)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name:
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

console.log:
Partial body: {"number":"1009732533765201"} { number: '1009732533765201' }
Body: {"number":"1009732533765201"} { number: '1009732533765201' } 1009732533765201

0 个答案:

没有答案