[英]Post JSON data in a HTML form
I am using React on the front-end & expressJs for server. 我在服务器的前端和expressJs上使用React。 I have some javascript
Object
data to send to the server. 我有一些JavaScript
Object
数据要发送到服务器。 I JSON.stringify
the data & then store it in <textarea/>
within the form & I then I just post it. 我对数据进行
JSON.stringify
,然后将其存储在表单中的<textarea/>
中,然后我将其发布。
I am using the modules 'body-parser' for general api calls & 'multer' for this multi-part form submission. 我正在将模块“ body-parser”用于常规api调用,将“ multer”用于此多部分表单提交。
Front-end code: 前端代码:
<div>
<form action="/api/query" method="POST">
{/* following textarea value looks like this:
{"collection":"Contract","fieldSets":[{"field":"location","value":"London","andOr":""}],"responseType":"csv"} */}
<textarea defaultValue={JSON.stringify({ collection, fieldSets, responseType: 'csv' })} />
<Button type="submit">Download</Button>
</form>
</div>
Back-end code: 后端代码:
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const app = express();
app.set('port', 1111);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
app.post('/query', (req, res) => {
// here I keep getting reqbody as an empty {}
console.log('reqbody is...', req.body);
However, I keep getting {}
within req.body
on the server. 但是,我不断在服务器的
req.body
获取{}
。 To clarify, the /api/query
does work as I am able to fetch
data from the url & display on front-end. 需要澄清的是,
/api/query
确实可以正常工作,因为我能够从url fetch
数据并在前端显示。 Its the form submission post which doesn't work. 它的表单提交帖子不起作用。
Thanks 谢谢
HTML form input fields should have a name
attribute to be accepted, otherwise they are ignored in the form submission. HTML表单输入字段应具有要接受的
name
属性,否则在表单提交中将被忽略。 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input
The above work with the following change: 上面的工作进行了以下更改:
...
// added name attribute
<textarea name="reqData" defaultValue={JSON.stringify({ collection, fieldSets, responseType: 'csv' })} />
...
JSON.stringify will just stringify the object. JSON.stringify只会对对象进行字符串化。 in your case looks like you are replacing the object.
在您的情况下,看起来您正在替换对象。 your syntax looks like
你的语法看起来像
JSON.stringify(obj, replacer, space)
better save your data in one variable and just stringify it by passing as first param to this. 最好将数据保存在一个变量中,并通过将其作为第一个参数传递来对其进行字符串化。
refer : https://www.w3schools.com/jsref/jsref_stringify.asp 参考: https : //www.w3schools.com/jsref/jsref_stringify.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.