这个Node.js REST API应用程式程式码片段有什么作用?

时间:2018-06-22 11:40:42

标签: javascript node.js rest api web-applications

function createData(req, res) {
  console.log('trying to store Data.')
  console.log('testing log ' + req.body.productID)

  app.create_data(req, function (err, response) {
    console.log('while returning' + response)
    console.log('while returning error is '+err)

    if(!err){
        var jsonString = {}
        jsonString['Result'] = "Success"

        res.setHeader('Content-Type', 'application/json')
        res.send(JSON.stringify(jsonString))
        res.end()
    }
    else{
        var jsonString = {}
        jsonString['Error'] = err.description

        res.setHeader('Content-Type', 'application/json')
        res.send(JSON.stringify(jsonString))
        res.end()
    }
  })
}
  1. 我已经在REST API示例中看到了以下用于创建数据的代码。我对此一无所知,有人可以解释一下此代码段的总体目的吗?

  2. jsonString['Result'] = "Success"在做什么,因为我们已经用空字符串初始化了?

  3. 这些是GET API,我的代码在哪里从文本字段获取数据?

  4. app在此Node.js代码段中是什么意思?

  5. 我们为什么要赋予已经使用的相同名称,例如:app.app.create_data

1 个答案:

答案 0 :(得分:1)

  1. 此代码段将创建对某些API路由的JSON响应。

  2. 此行在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><h4 id="quest"></h4></div> <div><input type="radio" name="answ" id="opt1" value="1"> <label for="opt1" id="ans1">a</label> <br> </div><br> <div><input type="radio" name="answ" id="opt2" value="2"> <label for="opt2" id="ans2">asd</label><br> </div><br> <div><input type="radio" name="answ" id="opt3" value="3"> <label for="opt3" id="ans3">asd</label><br> </div><br> <div><input type="radio" name="answ" id="opt4" value="4"> <label for="opt4" id="ans4">ccs</label><br> </div><br> <div><input type="radio" name="answ" id="opt5" value="5"> <label for="opt5" id="ans5">csc</label> <div id="next" style="float: right;">Next</div><br> </div> <div id="result"></div>键下将字符串值"Success"分配给jsonString对象。这是将键值对存储在JavaScript Object中的一种方法。

  3. 此代码段仅发送'Result'对象所保留的内容,即发送jsonString消息的"Result"或发送"Success"的对象说明。它将转换为JSON,并作为响应发送:"Error"

  4. 通常,“ app”是Node.js中some HTTP server的实例

  5. 这只是一种结构化/命名方式,这与项目之间的差异很大。


要开始使用Node.js应用程序,请查看以下链接: