Node Js-将数组转换为字符串并在其中添加斜杠 [英] Node Js - Converting array to string and adding slash to it

查看:133
本文介绍了Node Js-将数组转换为字符串并在其中添加斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习nodeJS.

I am learning nodeJS.

我尝试了其他stackoverlow问题和答案,但没有找到解决方案.我从最近两天开始就坚持这一点.

这是问题的开始

角度js代码:

$scope.queAns = [{"answer":"truyt","question":"How do you keep list elements straight in an HTML file?"},{"answer":"asc","question":"A sum of money at simple interest amounts to Rs. 815 in 3 years and to Rs. 854 in 4 years. The sum is:"}];
  $http({
    method : 'POST',
    url : "http://localhost:8888/answerList",
    withCredentials: true,
    data: $scope.queAns,
    headers : {'Content-Type' :  'application/x-www-form-urlencoded'}
  }).then(function (response) {
    console.log(response.data);
  }, function (error) {
    alert("Something went wrong.");
  });

NodeJs代码:

var http = require('http');
var fs = require('fs');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post('/answerList',urldecodedParser, function(req, res) {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(req.body);
})

我得到的输出为

{"{\"answer\":\"truyt\",\"question\":\"How do you keep list elements straight in an HTML file?\"},{\"answer\":\"asc\",\"question\":\"A sum of money at simple interest amounts to Rs. 815 in 3 years and to Rs. 854 in 4 years. The sum is:\"}":""}

我想输出为:

[{"answer":"truyt","question":"How do you keep list elements straight in an HTML file?"},{"answer":"asc","question":"A sum of money at simple interest amounts to Rs. 815 in 3 years and to Rs. 854 in 4 years. The sum is:"}]

有帮助吗?

推荐答案

在AJAX成为事物之前,网站在< form> 中使用了< input> 元素提出要求的元素.每个< input> 都有一个名称和一个 value ,它们被编码为:

Back before AJAX was a thing, websites used <input> elements inside <form> elements to make requests. Each <input> had a name and a value and they were encoded as:

name1=value1&name2=value2&name3=value3

如果< form> 是使用GET请求提交的,则此编码参数数据将仅附加到URL.另一方面,如果使用POST请求提交,则会使用 application/x-www-form-urlencoded content-type 作为请求正文发送

If the <form> was submitted using a GET request then this encoded parameter data would just be appended to the URL. On the other hand, if it was submitted using a POST request it would be sent as the request body using a content-type of application/x-www-form-urlencoded.

回到今天,这种格式仍然有效,并且仍然可以用于将数据传输到服务器.在Express中,中间件 bodyParser.urlencoded 会将使用 application/x-www-form-urlencoded 格式的请求正文解码为一个平面JS对象.使用上面的示例,您将得到如下结果:

Returning to the present day, this format is alive and well and can still be used to transmit data to a server. In Express the middleware bodyParser.urlencoded will decode request bodies that use the application/x-www-form-urlencoded format into a flat JS object. Using my example above you'd end up with something like this:

req.body = {
    name1: 'value1',
    name2: 'value2',
    name3: 'value3'
}

如果传递的参数没有值,例如 name1& name2 = value2 中的 name1 ,它将被视为值是空字符串,因此:

If a parameter is passed without a value, e.g. name1 in name1&name2=value2, it will be treated as though the value were an empty string, so:

req.body = {
    name1: '',
    name2: 'value2'
}

现在让我们假设我们发送JSON数据 {"answer":true} 作为请求正文,但我们错误地将 application/x-www-form-urlencoded 用于 content-type .解析器将把 {"answer":true} 与上一个示例中的 name1 相同,并将其解析为:

Now let's imagine we send the JSON data {"answer":true} as our request body but we incorrectly use application/x-www-form-urlencoded for the content-type. The parser will treat {"answer":true} just the same as name1 in our previous example and parse it into:

req.body = {
    '{"answer":true}': ''
}

在人类看来,这里显然存在一些JSON,但是对于解析器冷酷,无情的逻辑,文本 {"answer":true} 并没有特殊的意义,它只是将其视为参数名称.

To human eyes there's obviously some JSON going on here but to the cold, unforgiving logic of the parser the text {"answer":true} has no special significance, it just treats it as a parameter name.

如果我们然后尝试使用以下方法将其弹回响应中:

If we then try to bounce this back in the response using:

res.send(req.body);

它将进行JSON编码以给出响应:

it will be JSON encoded to give the response:

{"{\"answer\":true}":""}

这就是您所看到的,尽管使用的是更长的JSON.目前,我无法解释示例中方括号的位置,我希望在肢体上看到 [] ,但似乎有些东西正在消耗它们

This is what you're seeing, albeit with a much longer piece of JSON. Currently I can't explain where the square brackets have gone in your example, I'd expect to see [ and ] at the extremities but it would seem something is consuming them.

要解决此问题,我们首先需要修复我们的 content-type .而不是使用 application/x-www-form-urlencoded ,它应该是 application/json .然后,我们需要在服务器上使用适当的解析器,该解析器为 bodyParser.json ,例如:

To fix this we first need to fix our content-type. Rather than using application/x-www-form-urlencoded it should be application/json. Then we need an appropriate parser on the server, which would be bodyParser.json, e.g.:

app.post('/answerList', bodyParser.json(), function(req, res) {

通常, bodyParser 将被单独包含,因此可以被所有请求共享.仅 content-type application/json 的请求会受到影响,因此它不会对不使用JSON的请求造成任何不利影响:

Usually the bodyParser would be included separately so it can be shared by all requests. Only requests with a content-type of application/json would be affected so it shouldn't cause any adverse effects for requests that aren't using JSON:

app.use(bodyParser.json());

app.post('/answerList', function(req, res) {

我强烈建议您阅读 https://expressjs.com/上的文档zh/resources/middleware/body-parser.html

这篇关于Node Js-将数组转换为字符串并在其中添加斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆