这是有效的。
我能够通过 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 Script 作为后端。
我是否应该为此类内容设置 OAuth 令牌,如果是,如何设置?否则,我该怎么办这个问题?
现在,除了我的旧 Google Apps 脚本之外,没有任何后端。
在这种情况下,如何使用"Content-Type": "text/plain"
代替"Access-Control-Allow-Origin": "*"
如下?
headers: {
"Access-Control-Allow-Origin": "*",
},
headers: {
"Content-Type": "text/plain"
},
doPost(e)
您的 Google Apps 脚本端工作正常。当您的 Google Apps 脚本发生错误时,该错误可能无法删除。请注意这一点。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句