问题
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.
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 })
}
)
}
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"})
and just
{"status":"success"}
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 })
}
But I feel like that's not available to the result because of the way React packages things up.
Anyone know how I can actually get the result returned by the JSONP call?
回答1:
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>
来源:https://stackoverflow.com/questions/60764598/how-to-properly-implement-a-jsonp-form-post-submission-on-a-gatsby-site