【发布时间】:2018-08-24 09:09:07
【问题描述】:
我尝试使用我的 Angular 应用程序使用 firebase/sendgrid 配置电子邮件功能。按下按钮时调用函数
**--INDEX.JS**
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const SENDGRID_API_KEY = functions.config().sendgrid.key
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(SENDGRID_API_KEY);
exports.httpEmail = functions.https.onRequest((req, res) =>
{
cors(req, res, () =>
{
const toName = req.body.toName;
const toEmail = req.body.toEmail;
const msg = {
to: toEmail,
from: 'hello@angularfirebase.com',
subject: 'New Follower',
// text: `Hey ${toName}. You have a new follower!!! `,
// html: `<strong>Hey ${toName}. You have a new follower!!!</strong>`,
// custom templates
templateId: '300e1045-5b30-4f15-8c43-41754b73fe4f',
substitutionWrappers: ['{{', '}}'],
substitutions: {
name: toName
// and other custom properties here
}
};
return sgMail.send(msg)
.then(() => res.status(200).send('email sent!'))
.catch(err => res.status(400).send(err))
});
});
**--SendEmailComponent**
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from 'http';
@Component({
selector: 'app-send-email',
templateUrl: './send-email.component.html',
styleUrls: ['./send-email.component.css']
})
export class SendEmailComponent implements OnInit
{
//fields
endpoint = 'https://**blankblank**.cloudfunctions.net/httpEmail';
httpOptions =
{
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
}
//ctr
constructor(private http: HttpClient) { }
//lifehook
ngOnInit()
{
}
//methods
sendEmail()
{
const data =
{
toEmail: 'someone@something.net',
toName: 'Some One'
}
//post
this.http.post(this.endpoint, data, this.httpOptions).subscribe(data => console.log('email sent: ', data));
}
}
我尝试了不同的tutorials,但我总是收到此错误:
加载失败 https://blankblank.cloudfunctions.net/http电子邮件: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源
【问题讨论】:
标签: firebase cors http-headers google-cloud-functions sendgrid