如何在Gatsby网站上正确实施JSONP表单发布提交 [英] How to properly implement a JSONP form post submission on a Gatsby site
问题描述
我有一个用盖茨比创建的网站.其中一个页面上有一个表单,它需要发布到不支持CORS但支持JSONP的端点.
I've got a site, created with Gatsby. There is a form on one of the pages, and it needs to post to an endpoint that doesn't support CORS, but does support JSONP.
我已经使用 jsonp 编写了这样的事件处理程序:
I've written the event handler like this, using jsonp:
const handleSumbit = async event => {
event.preventDefault()
jsonp(
"https://go.pardot.com/form/id/code/",
{
timeout: 10000,
params: {
firstname: "fname",
lastname: "lname",
email: "an@email.com",
company: "company",
},
},
(err, data) => {
console.log({ err }, { data })
}
)
}
基于这篇帖子,我在上创建了2个静态文件我的网站称为error.json
和success.json
.我都尝试过这样的内容:
Based on this post, I created 2 static files on my site called error.json
and success.json
. I've tried content like this in both:
cb({"status":"succcess"})
还有
{"status":"success"}
我总是在控制台中收到一条错误消息,说请求超时,如果将结果包装在jsonpCb()
中,我也会收到一条错误消息,说Uncaught ReferenceError: jsonpCb is not defined
.我认为它工作了一半,因为它正在尝试运行该功能,并且正在保存表单数据.在我的React组件中,我创建了一个名为jsonpCb的函数:
I always get an error in the console saying the request timed-out, and if I wrap the result in jsonpCb()
I also get one saying Uncaught ReferenceError: jsonpCb is not defined
. I assume it's half working because it's trying to run that function, and the form data is being saved. In my React component I created a function called jsonpCb that's just this:
const jsonpCb = data => {
console.log("fromJsonCb", { data })
}
但是我觉得由于React将事情打包的方式,结果无法使用.
But I feel like that's not available to the result because of the way React packages things up.
任何人都知道我如何才能真正获得JSONP调用返回的结果吗?
Anyone know how I can actually get the result returned by the JSONP call?
推荐答案
我可以使jsonp与一起使用一个,它不如您使用的老.我将首先使用一个有效的示例(例如我正在使用的url)对其进行测试.
I could get jsonp working with this one, it isn't as old as the one you are using. I would test it first with a working example (like the url I am using).
const App = () => {
const [data, setData] = React.useState({
loading: true,
});
React.useEffect(() => {
const query = {
callback: 'myCallback',
url: 'https://jsonview.com/example.json',
};
fetchJsonp(
'https://jsonp.afeld.me/?' +
new URLSearchParams(query).toString()
)
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log('query was:', query);
setData(json);
})
.catch(function(ex) {
console.log('parsing failed', ex);
});
}, [setData]);
return <pre>{JSON.stringify(data, undefined, 2)}</pre>;
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch-jsonp/1.1.3/fetch-jsonp.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这篇关于如何在Gatsby网站上正确实施JSONP表单发布提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!