【发布时间】:2020-11-03 08:59:23
【问题描述】:
这很有效。
我能够通过 Google Apps 脚本创建一个端点,允许最终用户向我(或其他联系人)发布消息,并且还可以向他们发布该消息的副本。
POST 请求的代码类似于:
function doPost(e) {
var response;
try {
response = sendContactEmail(e.postData.contents);
}
catch (error) {
throw JSON.stringify(error, null, '\t');
}
return ContentService
.createTextOutput(JSON.stringify(response))
.setMimeType(ContentService.MimeType.JSON)
}
现在,当我尝试它时,我遇到了问题。当我从我的 Angular 站点尝试它时,服务代码如下:
@Injectable()
export class ContactService implements SenderService {
constructor(private http: HttpClient) {}
send(message: EmailMessage): Observable<any> {
return this.http.post<any>(
"https://script.google.com/macros/s/AKfycbyEuvROpXUEi4wTX4N06nqF6oHlwihVc9Ut6-OG04zPi5yuOCzn/exec",
JSON.stringify({ data: message }),
{
headers: {
"Access-Control-Allow-Origin": "*",
},
}
);
}
}
它不起作用,我面临类似的问题
Access to XMLHttpRequest at 'https://script.google.com/macros/s/AKfycbyEuvROpXUEi4wTX4N06nqF6oHlwihVc9Ut6-OG04zPi5yuOCzn/exec' from origin 'http://localhost:4200' 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.
在尝试调试此问题时,我打开 Postman,发出请求,却得到以下 HTML 响应:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="//ssl.gstatic.com/docs/script/images/favicon.ico">
<title>Error</title>
<style type="text/css">
body {
background-color: #fff;
margin: 0;
padding: 0;
}
.errorMessage {
font-family: Arial, sans-serif;
font-size: 12pt;
font-weight: bold;
line-height: 150%;
padding-top: 25px;
}
</style>
</head>
<body style="margin:20px">
<div><img alt="Google Apps Script" src="//ssl.gstatic.com/docs/script/images/logo.png"></div>
<div style="text-align:center;font-family:monospace;margin:50px auto 0;max-width:600px">Authorization is
required to perform that action.</div>
</body>
</html>
我不太了解使用 Google Apps 脚本作为后端。
我应该为这种类型的东西设置 OAuth 令牌吗?如果可以,如何设置? 否则,这个问题我该怎么办?
目前,除了我的旧版 Google Apps 脚本之外,没有任何后端。
【问题讨论】:
-
我提出了一个修改点作为答案。你能确认一下吗?在我的环境中,我可以确认脚本通过修改工作。但是在您的环境中,当它不起作用时,我为此道歉。
-
@TheMaster 在
axios.post的情况下,发现Content-Type是不需要的。 Ref 但是在我的环境中,好像在angular的情况下,当不使用Content-Type时,会出现与CORS相关的错误。 -
@Tanaike 正如那个答案中所说,我相信答案的本质是“避免预检”。不同的库可能会将不同的标头设置为默认值。但是只要将
Content-type设置为“text/plain”或任何其他使请求“简单请求”的mime 类型,它就应该避免cors 错误。这就是我在此处链接该答案的原因。 -
@TheMaster 感谢您的回复。我忘记了请求标头可能取决于每个库。在那种情况下,我可以理解需要修复内容类型。当我想到OP的情况时,我认为内容类型可能已经设置好了。这样,就需要使用内容类型。另外,我可以修改this。感谢您提供更多信息。
标签: angular google-apps-script xmlhttprequest cors