简体   繁体   English

如何使用node将表单数据(文本/纯文本)转换为json?

[英]How to convert form data (text/plain) to json with node?

I need to execute a POST call to an API to placce an order. 我需要执行对API的POST调用才能放置订单。 Herefore I made a simple Node js app. 因此,我制作了一个简单的Node js应用程序。 At the moment with this current state I receive text/plain data into our app, but this is not in JSON style. 目前处于这种当前状态,我将文本/纯文本数据接收到我们的应用程序中,但这不是JSON样式。

This is what I have now: 这就是我现在所拥有的:

TypeOrder=buy
Coin=BTC
AmountCoin=1
CoinPriceInEuro=100
CoinAddress=17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M
PaymentMethod=1
GeneralTermsAccepted=true

I want it in JSON (like): 我想要JSON(例如):

{
  "Email": "example1@1.nl",
  "Coin": "BTC",
  "CouponCode": "",
  "AmountEuro": 80.0,
  "AmountCoin": 1.0,
   "CoinPriceInEuro": 80,
  "CoinAddress": "17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M",
  "TypeOrder": "buy",
  "PaymentMethod": 1,
  "GeneralTermsAccepted": false
}

And attached you find the code. 并附上您找到的代码。

Can anyone tell what I have to do in order to get it in right json? 谁能说出我要做什么才能在正确的json中获得它?

 const express = require('express'); const http = require('http'); const app = express(); const fs=require('fs'); const hostname = '127.0.0.1'; const port = 3000; const bodyParser = require('body-parser'); var jsonParser = bodyParser.json() var urlencodedParser = bodyParser.urlencoded({ extended: false }) fs.readFile('index.html', (err, html) => { if(err) { throw err; } var server = http.createServer((req, res) => { res.statusCode=200; res.setHeader('Content-type', 'text/html'); res.write(html); res.end(); }); server.listen(port, hostname, () => { console.log('Server started on port'+port); }); // POST /login gets urlencoded bodies app.post('http://localhost:3030/rest/v1/PostOrder', urlencodedParser, function (req, res) { console.log(req.body); if (!req.body) return res.sendStatus(400); res.send('http://localhost:3030/rest/v1/PostOrder', {qs:req.query}); }); }); 
 <!DOCTYPE html> <html> <body> <form enctype="text/plain" action="http://localhost:3030/rest/v1/PostOrder" method="POST"> Buy/Sell:<br> <input type="text" name="TypeOrder" value="buy"> <br> Coin:<br> <input type="text" name="Coin" value="BTC"> Amount in Coin:<br> <input type="number" name="AmountCoin" value="1"> <br> Coin Price in Euro:<br> <input type="number" name="CoinPriceInEuro" value="100"> <br> Coin address to send:<br> <input type="text" name="CoinAddress" value="17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M"> <br> Payment method:<br> <input type="radio" name="PaymentMethod" value="1" checked> iDeal<br> <input type="radio" name="PaymentMethod" value="2"> Credit Card<br> <input type="radio" name="PaymentMethod" value="3"> PayPal<br> <br> Terms accepted:<br> <input type="radio" name="GeneralTermsAccepted" value="true" checked>Ja<br> <input type="radio" name="GeneralTermsAccepted" value="false">No<br> <br><br> <input type="submit" value="Submit"> </form> <p>If you click the "Submit" button, the form-data will be sent to a page called "/action_page.php".</p> </body> </htm 

So, you can do something like the following: 因此,您可以执行以下操作:

const data = `
    TypeOrder=buy
    Coin=BTC
    AmountCoin=1
    CoinPriceInEuro=100
    CoinAddress=17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M
    PaymentMethod=1
    GeneralTermsAccepted=true`;

let parts = data.split( '\n' );
let formattedData = {};

parts.forEach( ( part ) => {
    const splitData = part.split( '=' );
    formatterData[ splitData[ 0 ] ] = splitData[ 1 ];
} );

This is a very simple approach. 这是一个非常简单的方法。 You can make it more functionally oriented or simpler using a tonne of libraries. 您可以使用大量的库使它更加注重功能或更简单。 :) :)

The body data is separated by \\n , so you can split and then loop over that array. 主体数据用\\n分隔,因此您可以拆分然后在该数组上循环。

  • The payload_template is your empty template that will be filled with the body data. payload_template是您的空模板,将使用主体数据填充该模板。

Snippet 片段

 let body = `TypeOrder=buy Coin=BTC AmountCoin=1 CoinPriceInEuro=100 CoinAddress=17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M PaymentMethod=1 GeneralTermsAccepted=true`; let payload = {}; body.split('\\n').forEach((c) => [key, payload[key]] = c.split('=')); console.log(payload); 
 .as-console-wrapper { max-height: 100% !important } 

There is no need to specify the enctype as text/plain in your form. 无需在表单中将enctype指定为text / plain。

Just remove that properly since your node app is already using json encoder as a middleware. 只需将其正确删除即可,因为您的节点应用程序已在使用json编码器作为中间件。

what about this: 那这个呢:

 let str=`TypeOrder=buy Coin=BTC AmountCoin=1 CoinPriceInEuro=100 CoinAddress=17J6W29E2q94YNg5eiaHGsNWW9oJxsWu1M PaymentMethod=1 GeneralTermsAccepted=false`; let result=str.split('\\n').reduce((re, v) => { let key=v.split('=')[0],val=v.split('=')[1]; if (val.match(/^\\d+\\.\\d+$|^\\d+$/)) { val=Number(val); }else if(val.match(/^true$/i)){ val=true; }else if(val.match(/^false$/i)){ val=false; } re[key]=val; return re; }, {}); console.log(result); 

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

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