【发布时间】:2020-01-05 17:17:00
【问题描述】:
我正在尝试从我的组件状态中获取数据,然后将其发送到 REST api。我在 on submit 函数中创建了 axios post req,但是我知道这在 gatsby 中不起作用。当我从 Gatsby 的 onSubmit 函数发出请求时,我的 res.data 是“这个应用程序最适合 Javascript”。我想知道我可以从 Gatsby 发出发布请求的最佳方式是什么,以便我可以从组件的状态中传递数据。我一直在考虑将其用作我的 gatsby-node.js 文件,但是我不确定如何在其中获取组件的状态数据,以便可以在 post req 中使用它。谢谢。
提交函数
//submits answers to backend
Submit = () => {
let {answers} = this.state
axios
.post("/done", answers)
.then(res => this.setState({results:res.data,resultsStatus:true}))
.catch(
err => console.log(err)
);
};
要触发提交功能,我有一个加载 gif 弹出窗口 4 秒,然后触发提交功能。内容请求是组件返回的jsx
contentQuest = (
<div className = 'results-loading'>
Loading Results!
<img src={require('./images/loading.gif')} className='results-loading-gif'/>
</h2>
</div>
);
setTimeout(() => {
this.Submit()
},4000)
gatsby-node.js
// You can delete this file if you're not using it
const axios = require('axios');
const crypto = require('crypto');
exports.sourceNodes = async ({ boundActionCreators }) => {
const { createNode } = boundActionCreators;
// fetch raw data from the randomuser api
//Here I'm trying to change it to axios.post and grab component's state data
//not sure how to
const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
// await for results
const res = await fetchRandomUser();
// map into these results and create nodes
res.data.results.map((user, i) => {
// Create your node object
const userNode = {
// Required fields
id: `${i}`,
parent: `__SOURCE__`,
internal: {
type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
// contentDigest will be added just after
// but it is required
},
children: [],
// Other fields that you want to query with graphQl
gender: user.gender,
name: {
title: user.name.title,
first: user.name.first,
last: user.name.last,
},
picture: {
large: user.picture.large,
medium: user.picture.medium,
thumbnail: user.picture.thumbnail,
}
// etc...
}
// Get content digest of node. (Required field)
const contentDigest = crypto
.createHash(`md5`)
.update(JSON.stringify(userNode))
.digest(`hex`);
// add it to userNode
userNode.internal.contentDigest = contentDigest;
// Create node with the gatsby createNode() API
createNode(userNode);
});
return;
}
编辑: 我尝试将我的发布请求更改为此
fetch('http://localhost:5000/api/done', {
method: 'POST',
body: JSON.stringify(answers),
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}) .then(res => {
return res.json()})
.then(res => console.log(res))
.catch(
err => {
console.log(err)}
);
};
现在我的控制台中有这条消息:
从源“http://localhost:8000”获取“http://localhost:5000/api//done”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
【问题讨论】:
-
你能分享一些调用
onSubmit的组件吗?它是在表单中,还是在按钮中?完整的onSubmit函数长什么样子? -
@estevan 是的,没问题,我在帖子中添加了更多信息
标签: javascript reactjs rest axios gatsby