我正在尝试从客户端向服务器端发送电子邮件值,但我收到了一些错误。我的代码如下。
HTML
<form class="example-form" (ngSubmit)="uptpwd()">
<input class="form-control lht" placeholder="Email" type="email" name="email" [(ngModel)]="email">
<br/>
<br/>
<button class="lgbtn" type="submit">Enter</button>
</form>
TS
export class ForgotComponent implements OnInit {
email: string = '';
constructor(private auth: AuthService,
private formBuilder: FormBuilder,
private http: Http,
public toast: ToastComponent) { }
ngOnInit() {
}
uptpwd(email)
{
this.auth.uptpwd(this.email).subscribe();
}
}
服务
uptpwd(email){
return this.http.post(`http://localhost:3000/sendmail`,email).map(res =>
res.json());
}
服务器
app.post('/sendmail', function (req, res) {
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'f*******@gmail.com',
pass: *************
}
});
let mailOptions = {
from: *******@gmail.com
to:req.body.email,
subject: 'Password Reset',
text: 'Click the link to reset password: ',
};
app.options('/sendmail', function (req, res) {
res.sendStatus(200);
});
res.setHeader('Access-Control-Allow-Origin', 'localhost:4200/forgot'); // Change this to your Angular 2 port number
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', '*');
transporter.sendMail(mailOptions, (error, info) =>
{
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s',
info.messageId, info.response);
});
})
错误:无法加载资源:服务器响应状态为500(内部服务器错误) 忘记:1无法加载http://localhost:3000/sendmail:请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:4200”访问。响应的HTTP状态代码为500。
答案 0 :(得分:0)
尝试这样做,我遇到了同样的错误,我按照以下方式使其工作,
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});