我已经在Angular 7.0.5项目中添加了cors标头,但是在提交表单并将表单数据发送到“后端”(Google脚本)时,仍然出现以下错误:
从原点“ https://script.google.com/blabla”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。
在禁用安全性的Chrome中尝试此错误时,我没有收到此错误。
可能是语法错误,但是我已经搜索了很长时间,尝试了很多尝试,但是我无法使其正常工作。
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient, HttpParams, HttpHeaders} from '@angular/common/http';
import {ContactFormDto} from '../services/dto/contactform.dto';
const headers = new HttpHeaders()
.set('Content-Type', 'undefined')
.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'POST')
.set('Access-Control-Allow-Headers', 'Origin')
.set('Access-Control-Allow-Credentials', 'true');
@Component({
selector: 'app-contact',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.sass']
})
export class ContactComponent implements OnInit {
contactForm: FormGroup;
submitted = false;
MAIL_SCRIPT_URL =
'https://script.google.com/scriptlocation';
private contactFormDto: ContactFormDto;
constructor(private formBuilder: FormBuilder, private http: HttpClient) {
this.contactForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', Validators.required],
message: ['', Validators.required],
});
}
onSubmit() {
this.submitted = true;
if (this.contactForm.valid) {
this.contactFormDto = new ContactFormDto(
this.contactForm.controls.name.value,
this.contactForm.controls.email.value,
this.contactForm.controls.message.value
);
this.http.post(
this.MAIL_SCRIPT_URL,
this.contactFormDto,
{headers}
).subscribe(data => {
console.log('Mail has been sent' + data);
}, error => {
console.log('Mail has not been sent ' + error);
});
console.log('name: ' + this.contactForm.controls.name.value + ' email: ' +
this.contactForm.controls.email.value + ' message: ' +
this.contactForm.controls.message.value);
}
}
ngOnInit() {
}
“后端”是Google脚本(当我将表单结果发布到url时运行)
var TO_ADDRESS = "myaddress@gmail.com"; // where to send form data
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class
Logger
MailApp.sendEmail(TO_ADDRESS, "Contact Form Submitted",
JSON.stringify(e.parameters));
// return json success results
return ContentService
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
答案 0 :(得分:-1)
如果您想以最简单的方式使用插件。
Allow-Control-Allow-Origin