可以通过Axios和节点后端发送数据

发布于 2025-02-11 19:49:27 字数 596 浏览 1 评论 0原文

我正在尝试访问从后端传递到前端的表达式,并通过Axios访问前端。

生产者方面:

const axios = require('axios');
const URL = "http://localhost:5000/"
let n1 = 3
let n2 = 5
let sum = n1+n2;



axios.post(URL, JSON.stringify({
    expression: sum,
  }))
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

在消费者方面:

const express = require('express')
const app = express()

app.post('/', (req, res) => {
  console.log(req.body);
})

app.listen(5000, () => console.log())

最终,我想拥有消费者侧日志“ 8”

I am trying to access the expression passed from the backend to the frontend through axios.

Producer side:

const axios = require('axios');
const URL = "http://localhost:5000/"
let n1 = 3
let n2 = 5
let sum = n1+n2;



axios.post(URL, JSON.stringify({
    expression: sum,
  }))
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

and on the consumer side:

const express = require('express')
const app = express()

app.post('/', (req, res) => {
  console.log(req.body);
})

app.listen(5000, () => console.log())

Ultimately, I would like to have the consumer side log "8"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

随波逐流 2025-02-18 19:49:27

您无需转换为JSON,Axios本地服务JSON。

添加到服务器:

app.use(express.json())

只需向您发送数据:

axios.post(URL, { expression: sum, })
  .then(console.log)
  .catch(console.err)

You don't need to convert to JSON, axios serves JSON natively.

Add to the server:

app.use(express.json())

Just send you data:

axios.post(URL, { expression: sum, })
  .then(console.log)
  .catch(console.err)
成熟稳重的好男人 2025-02-18 19:49:27

来自“ express”文档

req.body

包含请求主体中提交的数据的键值对。默认情况下,它是 未定义的 ,当您使用诸如Body-Parser和Multer之类的身体脱落中间件时会填充。

在尝试注册端点之前,请尝试包括此内容:

const bodyParser = require('body-parser')

app.use(bodyParser.json())

您还可以使用express.json()并删除“身体偏好器”依赖项:

// const bodyParser = require('body-parser')

app.use(express.json())

From the "express" documentation:

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

Try including this before you try to register the endpoint:

const bodyParser = require('body-parser')

app.use(bodyParser.json())

You can also use express.json() and drop the 'body-parser' dependency:

// const bodyParser = require('body-parser')

app.use(express.json())
靖瑶 2025-02-18 19:49:27

Axios也有一些安全措施,您应该将IP地址放入
const url =“ http:// localhost:5000/”

Axios have some security measures as well, you should put your IP address in
const URL = "http://localhost:5000/"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文