React中用Fetch向Google Apps Script POST数据遇CORS问题求助
我是编程新手,已查阅资料一整天,但仍无法解决问题,恳请帮助。我尝试将React项目中的对象数据POST到Google Apps Script。
Apps Script代码
var ss = SpreadsheetApp.getActiveSpreadsheet(), Rcm = ss.getSheetByName("Rcm"); // "Rcm"是工作表名称 function doPost(e) { var para = e.parameter, method = para.method; if (method == "write") { write_data(para); } } function write_data(para) { var name = para.name, email = para.email, wechat = para.wechat; degree = para.degree; program = para.program; Rcm.appendRow([name, email, wechat ,degree ,program]); }
React组件代码
在React中,我有一组合并后的对象数据:
const contactAll = { ...contact, ...{name}, ...{pronoun}, ...{degree}, ...{program}, ...{recommender}, ...{position}, ...{organisation}, ...{profession}, ...{wording}, ...{relationship}, ...{recommend} };
我编写了向Google Apps Script发送POST请求的代码,为解决CORS问题将Content-Type从application/json改为text/plain,但仍出现错误:
let uri = "https://script.google.com/macros/s/AKfyc....gEOkUE8S42eZ_k5CGVAUQXw/exec"; const navigate = useNavigate(); const handleFetch = ( uri , data ) => {fetch( uri , { method: "Post", headers: { "Content-Type": "text/plain" }, body: JSON.stringify( data ) }).then( ()=>{ console.log("data added"); }).catch((error)=>{ console.error('Error:', error); }) }; const handleSecSubmit = (e) => { e.preventDefault(); handleFetch( uri , contactAll ); navigate("/final", { state: { contactAll } }); }
控制台输出
出现三个错误:
Access to fetch at 'https://script.google.com/macros/s/AKfycbw...S42eZ_k5CGVAUQXw/exec' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
POST https://script.google.com/macros/s/AKfycbwpQ...E8S42eZ_k5CGVAUQXw/exec net::ERR_FAILED 200
Second.js:55 Error: TypeError: Failed to fetch at handleFetch (Second.js:47:1) at handleSecSubmit (Second.js:62:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) at invokeGuardedCallback (react-dom.development.js:4277:1) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1) at executeDispatch (react-dom.development.js:9041:1) at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1) at processDispatchQueue (react-dom.development.js:9086:1) at dispatchEventsForPlugins (react-dom.development.js:9097:1)
疑问
请问我遗漏了什么?应该重点学习哪些知识?
内容的提问来源于stack exchange,提问作者FormosaMephitis

