我如何将数据从 ReactJS 提交表单传递给 AdonisJS
How can i pass data from ReactJS submit form to AdonisJS
我在 ReactJS 中有一个表单,每次单击提交按钮时,数据都应该传递给 adonis api。
ReactJs 文件
async handleSubmit(e) {
e.preventDefault();
console.log(JSON.stringify(this.state));
await axios({
method: 'post',
url: 'http://127.0.0.1:3333/add',
data: JSON.stringify(this.state),
})
.then(function (response) {
console.log('response',response);
})
.catch(function (error) {
console.log('error',error);
});
}
"http://127.0.0.1:3333/add" 是具有路由 '/add'
的 Adonis 服务器
我不知道如何在 Adonis 中写入 post 这条路线上的州
有人可以解释一下吗?
在控制器的函数中这样获取值
const data = request.only(['data'])
然后你得到数据。
像这样获取数据的其他方法
const alldata = request.all()
这个控制台这个结果并查看你得到了多少结果
并从此 alldata.data
获取数据
首先,创建一个简单的控制器来处理从 ReactJS 应用中的 handleSubmit()
方法接收的数据。
使用以下命令创建一个简单的控制器:
adonis make:controller TestController --type http
创建后,打开 TestController
文件并创建一个 index
方法并在 index
方法中添加以下内容。
'use strict'
class TestController{
// define your index method here
index ({ request }) {
const body = request.post() // get all the post data;
console.log(body) //console it to see the passed data
}
}
module.exports = TestController
之后,在 start/routes.js
文件中注册您的 /add
路由。
Route.post('/add', 'TestController.index') // controller name and the method
最后,点击 ReactJS 应用中的“提交”按钮,并对其进行测试。
Most likely you be getting CORS issues
when you send the request
from your ReactJS app to Adonis server, If so you have to proxy
the api
request to Adonis server.
为此,请在 ReactJS 应用程序中打开您的 package.json
文件,并添加以下 proxy field
.
"proxy": "http://127.0.0.1:3333",
我在 ReactJS 中有一个表单,每次单击提交按钮时,数据都应该传递给 adonis api。
ReactJs 文件
async handleSubmit(e) {
e.preventDefault();
console.log(JSON.stringify(this.state));
await axios({
method: 'post',
url: 'http://127.0.0.1:3333/add',
data: JSON.stringify(this.state),
})
.then(function (response) {
console.log('response',response);
})
.catch(function (error) {
console.log('error',error);
});
}
"http://127.0.0.1:3333/add" 是具有路由 '/add'
的 Adonis 服务器我不知道如何在 Adonis 中写入 post 这条路线上的州
有人可以解释一下吗?
在控制器的函数中这样获取值
const data = request.only(['data'])
然后你得到数据。像这样获取数据的其他方法
const alldata = request.all()
这个控制台这个结果并查看你得到了多少结果 并从此alldata.data
获取数据
首先,创建一个简单的控制器来处理从 ReactJS 应用中的 handleSubmit()
方法接收的数据。
使用以下命令创建一个简单的控制器:
adonis make:controller TestController --type http
创建后,打开 TestController
文件并创建一个 index
方法并在 index
方法中添加以下内容。
'use strict'
class TestController{
// define your index method here
index ({ request }) {
const body = request.post() // get all the post data;
console.log(body) //console it to see the passed data
}
}
module.exports = TestController
之后,在 start/routes.js
文件中注册您的 /add
路由。
Route.post('/add', 'TestController.index') // controller name and the method
最后,点击 ReactJS 应用中的“提交”按钮,并对其进行测试。
Most likely you be getting
CORS issues
when you send the request from your ReactJS app to Adonis server, If so you have toproxy
theapi
request to Adonis server.
为此,请在 ReactJS 应用程序中打开您的 package.json
文件,并添加以下 proxy field
.
"proxy": "http://127.0.0.1:3333",