首页 > 解决方案 > 为什么我有 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

标签: node.jsangularexpress

解决方案


正如我在评论中提到的:您需要将后端的完整 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`,{ ... });
  }
}

我的代码不准确,您需要根据需要进行安排。但是,我希望你明白这一点。


推荐阅读