node.js - 为什么我有 404 错误(Angular 2 和 Node js)
问题描述
我的网站上有一个表格,我想将字段中的数据发送到我的电子邮件。我正在使用 nodemailer 和 node js 来做这件事。但是当我提交表单时,POST 请求出现 404 错误。表单组件:
this.http.post('api/sendForm',{
to: environment.contactUsEmail,
from: 'zzz',
subject: 'zzz',
mailInfo: contactUsData,
}
).subscribe(() => {
this.cooperationFormGroup.reset();
});
server.ts: (path:backend/server.ts) 文件夹后端在文件夹 src 附近
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('api/sendForm', (req, res) => {
const payload = req.body;
const mailInfo = payload.mailInfo;
const transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
secure: 'true',
port: '465',
auth: {
user: 'email',
pass: 'pass',
}
});
const text = [...];
const mailOptions = {
from: 'zz',
to: payload.to,
subject: payload.subject,
text: text.join('\n'),
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
res.status(200).json({
message: 'successfully sent!'
})
}
});
});
app.listen(PORT, () => {
console.log(`Server is running in ${PORT}`);
});
我使用 node server.ts 在文件夹后端运行 server.ts 并使用 npm start 运行 angular app
解决方案
正如我在评论中提到的:您需要将后端的完整 URL 传递给post
: usehttp://localhost:3000/api/sendForm
而不是api/sendForm
.
但是,要在开发和生产期间管理不同的值,您可能需要使用environment.ts 和 environment.prod.ts:
环境/environment.ts:
export const environment = {
production: false,
urlToBackend: 'http://localhost:3000'
}
环境/environment.prod.ts:
export const environment = {
production: true,
urlToBackend: 'http://<IP>:3000'
}
服务.ts:
在使用 构建生产构建时npm run build
, environment.ts 将被 angular.json 中提到的 environment.prod.ts 替换(请参阅 object fileReplacements
)。
import { environment } from '../../environments/environment';
...
@Injectable()
export class AppService {
url = environment.urlToBackend;
constructor(private http: HttpClient) {
}
foo() {
return this.http.post(`${this.url}/api/sendForm`,{ ... });
}
}
我的代码不准确,您需要根据需要进行安排。但是,我希望你明白这一点。
推荐阅读
- django - 在 Django 的模板标签中无法访问用户变量
- python-3.x - Python Mqtt client.loop_forever 如何跳转n行
- angular - Angular 中未显示的属性
- deep-learning - 输入张量和隐藏张量不在同一个设备上,发现输入张量在 cuda:0 和隐藏张量在 cpu
- c# - DataTable:如果是 Db 中的 Date 字段,则在 UI 上仅显示 date 而不是 datetime
- reactjs - 如何通过索引从对象中推断元素?
- r - 如何在R中提取带有特殊字符的模式之间的字符串
- chef-infra - Powershell_Script with Guard Interpreter -> Action RUN everytime
- json - Django 嵌套文档序列化程序问题
- php - Laravel 图像不会显示