node.js - Angular 6 和 Nodejs : No 'Access-Control-Allow-Origin' header is present on the requested resource

标签 node.js angular typescript express bootstrap-4

我在 Angular 6 应用程序和 NodeJS 中有表单,当我提交表单时出现以下错误:

无法加载http://localhost:3000/contact/send:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。因此,不允许访问源“http://localhost:4200”。 我搜索并检查了其他类似的错误,但我无法摆脱该错误:(

这是 server.js

    // server.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const path = require('path');
    const app = express();
    // Port Number
    const port = process.env.PORT || 3000
    // Run the app by serving the static files
    // in the dist directory
    app.use(express.static(path.join(__dirname, '/majeni/dist/majeni')));
    // Body Parser Middleware
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    //routes
    const contact = require('./app/routes/contact');
    app.use('/contact', contact);
    // CORS Middleware
    app.use(cors());
    // If an incoming request uses
    // a protocol other than HTTPS,
    // redirect that request to the
    // same url but with HTTPS
    const forceSSL = function () {
      return function (req, res, next) {
        if (req.headers['x-forwarded-proto'] !== 'https') {
          return res.redirect(
            ['https://', req.get('Host'), req.url].join('')
          );
        }
        next();
      }
    }

    // Instruct the app
    // to use the forceSSL
    // middleware
    app.use(forceSSL());

    // For all GET requests, send back index.html
    // so that PathLocationStrategy can be used
    app.get('/*', function (req, res) {
      res.sendFile(path.join(__dirname + '/majeni/dist/majeni/index.html'));
    });

    // Start Server
    app.listen(port, () => {
        console.log('Server started on port '+port);
      });

这是路由( Node 邮件程序的 contact.js)

const express = require('express');
const router = express.Router();
const request = require('request');
const nodemailer = require('nodemailer');

router.get('/send', (req, res) => {
    const outputData = `
    <p>You have a new contact request</p>
    <h3>Contact Details</h3>
    <ul>  
      <li>Name: ${req.body.name}</li>
      <li>Email: ${req.body.email}</li>
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
  `;

    let transporter = nodemailer.createTransport({
        service: 'gmail',
        secure: false,
        port: 25,
        auth: {
            user: 'MY EMAIL',
            pass: 'THE PASSWORD'
        },
        tls: {
            rejectUnauthorized: false
        }
    });

    let HelperOptions = {
        from: '"MYNAME" <MYEMAIL,
        to: 'MYEMAIL',
        subject: 'Majeni Contact Request',
        text: 'Hello',
        html: outputData
    };



    transporter.sendMail(HelperOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log("The message was sent!");
        console.log(info);
    });

});
module.exports = router;

注意:我已经通过 npm 安装了 cors 并尝试了其他方法,但没有任何结果。

我的代码中缺少什么?

最佳答案

修复

只需确保使用 options 启用 cors 预检,并在调用前启用 header :

router.options('/send', cors()); // ADDED 
router.get('/send', cors(), (req, res) => { // ADDED

关于node.js - Angular 6 和 Nodejs : No 'Access-Control-Allow-Origin' header is present on the requested resource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068069/

相关文章:

android - React Native on Android : Cannot run program "node": error=2, 没有这样的文件或目录

typescript - 从包中修改命名空间

node.js - 将 oauth 与 node-webkit 结合使用

node.js - NPM 安装——将文件复制到其他文件夹

html - CSS 定位和列表项的问题

java - 为什么我在尝试从 angular5 向 spring-boot 发送 PUT 请求时收到未经授权的消息?

javascript - 如何在 Angular 2 中编写窗口关闭事件处理程序?

javascript - Angular CLI 删除箭头函数?

javascript - 在 Sails.js 中更新用户模型时密码被更改

node.js - 部署 Angular 2 项目时,Azure 持续部署在 Github 上失败