如何使用 axios 将字符串发送到快速服务器
How to send a string to an express server with axios
我是网络开发的新手,所以非常感谢任何帮助。
我需要向服务器发送纯文本,以便我可以对其应用 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')
}
})
}
最后,我通过发回新数据来处理 post 请求
app.post('/tolatex', toLatex, function (req, res) {
res.send(req.LaTeX)
})
阅读了一些文献后,我的理解是我从客户端发送的文本将在 req.body
中,但是 console.log(req.body)
的输出是 [=19= 形式的对象] 其中 text
是我从客户端发送的文本。然后,节点立即崩溃并显示消息 TypeError: Cannot convert object to primitive value
非常感谢您的指导。
更新: 一些探索让我相信
app.use(bodyParser.urlencoded({ extended: false }))
应替换为
var jsonParser = bodyParser.json()
app.use(jsonParser)
纯文本应该包裹在一个对象中e.g. {plaintext: text}
。这似乎工作正常。我得出的结论是我们不能 POST 一个简单的字符串吗?
您的文本变量的类型是什么?它应该是带有字段文本的对象,然后你可以用 req.body.text..
提取它
根据您的更新,我认为您应该始终向服务器发送一个带有键和值的对象,然后在服务器端您可以使用必要的键从您的请求正文中提取具体数据。
我是网络开发的新手,所以非常感谢任何帮助。
我需要向服务器发送纯文本,以便我可以对其应用 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')
}
})
}
最后,我通过发回新数据来处理 post 请求
app.post('/tolatex', toLatex, function (req, res) {
res.send(req.LaTeX)
})
阅读了一些文献后,我的理解是我从客户端发送的文本将在 req.body
中,但是 console.log(req.body)
的输出是 [=19= 形式的对象] 其中 text
是我从客户端发送的文本。然后,节点立即崩溃并显示消息 TypeError: Cannot convert object to primitive value
非常感谢您的指导。
更新: 一些探索让我相信
app.use(bodyParser.urlencoded({ extended: false }))
应替换为
var jsonParser = bodyParser.json()
app.use(jsonParser)
纯文本应该包裹在一个对象中e.g. {plaintext: text}
。这似乎工作正常。我得出的结论是我们不能 POST 一个简单的字符串吗?
您的文本变量的类型是什么?它应该是带有字段文本的对象,然后你可以用 req.body.text..
提取它根据您的更新,我认为您应该始终向服务器发送一个带有键和值的对象,然后在服务器端您可以使用必要的键从您的请求正文中提取具体数据。