将数据发布到 Web 应用程序时,XMLHttpRequest 被 CORS 策略阻止 [英] XMLHttpRequest blocked by CORS policy when posting data to a Web App
问题描述
当我尝试通过 Web 应用程序将数据发布到我的 Google 电子表格时,我收到了 CORS
错误响应.这是我得到的错误:
从源 'http://localhost:3000' 访问 XMLHttpRequest at 'myGoogleSpreadSheetApiURL' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin'请求的资源上存在标头.
我做了一些解决方案,我在互联网上搜索,但我无法解决问题...我已经可以从 Google 电子表格中获取我的 JSON 数据.
当我按下我的 createButton
时,我可以在我的 Google 电子表格上发布和写入我的数据.
我应该如何修复我的代码?你有什么想法吗?
这是我的 react.js 代码:
import React,{ Component } from 'react';从'@material-ui/core/Paper' 导入纸张;从 'axios' 导入 axios;axios.defaults.baseURL = 'http://localhost:3000';axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';const api = 'https://myGoogleSpreadSheetApiUrl';类价格扩展组件{状态 = {信息:[]};构造函数(){极好的()axios.get(api).then((res) =>{控制台日志(res.data)this.setState({信息:res.data})})};创建信息 = () =>{让 res = axios.post(api,{编号:100,产品:product100",价格:1000,miniLot: 1000,})控制台日志(res)}使成为(){返回 (<div><button onClick={this.createInfo}>createButon</button><纸>{this.state.info.map(info => <p key={info.id}>{info.product}</p>)}</纸>
);}}出口默认价格;
这是我的 Google Apps 脚本代码:
function getData(priceDB) {var sheet = SpreadsheetApp.getActive().getSheetByName(priceDB);var rows = sheet.getDataRange().getValues();var 键 = rows.splice(0, 1)[0];返回行.地图(功能(行){var obj = {};row.map(function(item, index) {obj[String(keys[index])] = String(item);});返回对象;});}函数 doGet() {var data = getData('DBprice');返回 ContentService.createTextOutput(JSON.stringify(data, null, 2)).setMimeType(ContentService.MimeType.JSON);}函数 doPost(e) {var ss = SpreadsheetApp.getActiveSpreadsheet();var sheet = ss.getSheetByName('DBprice');var PostData = JSON.parse(e.postData.contents);sheet.appendRow([PostData.id, PostData.product, PostData.price]);}
Google apps script web-application 目前仅支持以下 HTTP 方法:
POST
GET
OPTIONS
方法.因此,如果来自您的 React 网络应用程序的请求是预检, 请求将失败(http-status-code-405).为避免预检,请考虑将帖子正文和 Content-Type
更改为以下类型之一(所谓的 简单请求):
- application/x-www-form-urlencoded
- multipart/form-data
- 文本/纯文本
此外,为了避免重定向到 html 页面,您应该从服务器端return
文本.
客户端:
axios.defaults.headers.post['Content-Type'] = 'text/plain';/*....*/创建信息 = () =>{让 res = axios.post(api,JSON.stringify({编号:100,产品:product100",价格:1000,miniLot: 1000,}))//console.log(res)}
服务器端:
function doPost(e) {/*东西*/返回 ContentService.createTextOutput(完成");}
I get a CORS
error response when I tried to post my data to my Google Spreadsheet via a Web App. This is the error I get:
Access to XMLHttpRequest at 'myGoogleSpreadSheetApiURL' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I did some solution, I searched on internet but I can't solve the issue... I could already get my JSON data from the Google Spreadsheet.
When I push my createButton
, I can post and write my data on my Google Spreadsheet.
How should I fix my code ? Do you have any idea ?
This is my react.js code:
import React,{ Component } from 'react';
import Paper from '@material-ui/core/Paper';
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
const api = 'https://myGoogleSpreadSheetApiUrl';
class Price extends Component {
state = {
info: []
};
constructor(){
super()
axios.get(api)
.then((res) =>{
console.log(res.data)
this.setState({
info: res.data
})
})
};
createInfo = () =>{
let res = axios.post(api,{
id: 100,
product: "product100",
price: 1000,
miniLot: 1000,
})
console.log(res)
}
render(){
return (
<div>
<button onClick={this.createInfo}>createButon</button>
<Paper>
{this.state.info.map(info => <p key={info.id}>{info.product}</p>)}
</Paper>
</div>
);
}
}
export default Price;
and this is my Google Apps Script code:
function getData(priceDB) {
var sheet = SpreadsheetApp.getActive().getSheetByName(priceDB);
var rows = sheet.getDataRange().getValues();
var keys = rows.splice(0, 1)[0];
return rows.map(function(row) {
var obj = {};
row.map(function(item, index) {
obj[String(keys[index])] = String(item);
});
return obj;
});
}
function doGet() {
var data = getData('DBprice');
return ContentService.createTextOutput(JSON.stringify(data, null, 2))
.setMimeType(ContentService.MimeType.JSON);
}
function doPost(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('DBprice');
var PostData = JSON.parse(e.postData.contents);
sheet.appendRow([PostData.id, PostData.product, PostData.price]);
}
Only the following HTTP methods are supported by Google apps script web- application currently:
POST
GET
OPTIONS
method is currently not supported. So, if requests from your React web-app is preflighted, the requests will fail(http-status-code-405). To avoid preflighting, consider changing the post body and Content-Type
to one of the following types(so called Simple requests):
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
Also, In order to avoid redirection to a html page, you should return
text from the server side.
Client side:
axios.defaults.headers.post['Content-Type'] = 'text/plain';
/*....*/
createInfo = () =>{
let res = axios.post(api,JSON.stringify({
id: 100,
product: "product100",
price: 1000,
miniLot: 1000,
})
)
//console.log(res)
}
Server side:
function doPost(e) {
/*Stuff*/
return ContentService.createTextOutput("done");
}
这篇关于将数据发布到 Web 应用程序时,XMLHttpRequest 被 CORS 策略阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!