如何使用axios将string发送到快速服务器

我是新来的网页开发,所以任何帮助,非常感谢。

我需要发送一个纯文本到服务器,所以我可以将MathJax应用到它。

sendForTeX (text) { console.log('Sending ' + text + ' to be converted to LaTeX...') axios.post('/tolatex', text) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error) }) } 

在服务器端,我首先使用body-parser

 app.use(bodyParser.urlencoded({ extended: false })) 

然后,我定义一个中间件来排版文本。

 function toLatex (req, res, next) { console.log(req.body) MathJax.typeset({ math: req.body, format: 'TeX', svg: true, mml:false, }, function (data) { if (!data.errors) { req.LaTeX = data return next() } else { console.log('BRRRRUUU') } }) } 

最后,我通过发回新的数据来处理发布的请求

 app.post('/tolatex', toLatex, function (req, res) { res.send(req.LaTeX) }) 

阅读了一些文献后,我的理解是,我从客户端发送的文本将在req.body ,但是console.log(req.body)的输出是表单text: ''一个对象text: ''其中text是我从客户端发送的文本。 然后,节点立即崩溃,消息TypeError: Cannot convert object to primitive value

我真的很感谢这里的一些指导。

更新:一些戳穿让我相信

 app.use(bodyParser.urlencoded({ extended: false })) 

应该被replace

 var jsonParser = bodyParser.json() app.use(jsonParser) 

而纯文本应该包裹在一个对象中, eg {plaintext: text} 。 这似乎工作正常。 我的结论是我们不能张贴一个简单的string是正确的吗?

什么是你的文本variables的types? 它应该是字段文本的对象,然后你可以用req.body.text提取它。

根据你的更新,我认为你应该总是向服务器发送一个带有键和值的对象,然后在服务器端,你可以从你的请求体中提取具体的数据,并用必要的键。