简体   繁体   English

在Claudia JS框架中无法正确解析请求对象

[英]Request object not parsed correctly in Claudia JS framework

i want to build an API as a serverless AWS Lambda Function and use ClaudiaJS as a framework. 我想将API构建为无服务器的AWS Lambda函数,并使用ClaudiaJS作为框架。 However, when passing a JSON object to the POST route, i cannot parse the contents of request.body correctly since they are of the type "string" instead of type "object". 但是,当将JSON对象传递到POST路由时,我无法正确解析request.body的内容,因为它们的类型是“字符串”而不是“对象”类型。 If this were an express node.js backend, i would just use bodyParser, but in this case i cannot. 如果这是一个明确的node.js后端,我将只使用bodyParser,但在这种情况下我不能。 Any help appreciated :) 任何帮助表示赞赏:)

I tried JSON.parse(req.body), but to no avail. 我尝试了JSON.parse(req.body),但无济于事。

This is the code for the POST route 这是POST路线的代码

var ApiBuilder = require('claudia-api-builder'),
api = new ApiBuilder();

module.exports = api;

api.post('/upload', (req, res) => {
  return req.body;           //I return the body for debugging purposes 
});

When posting the JSON Object to the service using POSTMAN (content-type:application/json) 使用POSTMAN将JSON对象发布到服务时(content-type:application / json)

{
  "latitude": "52.514818",
  "longitude": "13.356101",
  "additionalData": "xyc"
}

it returns a string instead of an object. 它返回一个字符串而不是一个对象。 I therefore cannot parse it like: req.body.latitude and get the value for the latitude. 因此,我无法像req.body.latitude这样解析它并获取纬度值。

"----------------------------641080260577727375179249\r\nContent-Disposition: form-data; name=\"file\"; filename=\"Berlin.json\"\r\nContent-Type: application/json\r\n\r\n{\n  \"latitude\": \"52.514818\",\n  \"longitude\": \"13.356101\",\n  \"additionalData\": \"xyc\"\n}\n\r\n----------------------------641080260577727375179249--\r\n"

The issue you have, is that you are sending your API form data and expecting it to behave like JSON. 您遇到的问题是,您正在发送API表单数据,并希望它的行为类似于JSON。

The easiest solution would be to send the actual JSON in the POST body, in which case your existing code will work. 最简单的解决方案是在POST正文中发送实际的JSON,在这种情况下,您现有的代码将起作用。

Otherwise you will just have to grab the JSON from the existing string. 否则,您只需要从现有字符串中获取JSON。

var ApiBuilder = require('claudia-api-builder'), api = new ApiBuilder();
module.exports = api;

api.post('/upload', (req, res) => {
  console.log(req.body);  // outputs the form-data as string
  var myString = req.body.substring(
    req.body.lastIndexOf("{"), 
    req.body.lastIndexOf("}")+1
  );
  var myJson = JSON.parse(myString);
  console.log(myJson) // outputs a valid JSON object
  return myObj;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM