【问题标题】:Angular 6 and Nodejs: No 'Access-Control-Allow-Origin' header is present on the requested resourceAngular 6 和 Nodejs:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-02-03 16:32:40
【问题描述】:

我在 angular 6 app 和 nodejs 中有表单,当我提交表单时出现以下错误:

Failed to load http://localhost:3000/contact/send: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. 我搜索并检查了其他类似的错误,但我无法摆脱错误:(

这里是 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 mailer 的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 并尝试了其他方法但没有。

我的代码中缺少什么?

【问题讨论】:

    标签: node.js angular typescript express bootstrap-4


    【解决方案1】:

    修复

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

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

    【讨论】:

    • 更改我收到此错误OPTIONS http://localhost:3000/contact/send 0 ()
    • 还是一样,可能我可以给你发repo,你可以检查一下:(
    【解决方案2】:

    移动你的 app.use(cors());上面app.use(‘/contact’,contact);

    【讨论】:

    • 另外,如果您想要更精细地控制 CORS 访问,请移动 'const cors = require('cors');进入contact.js文件并将其用作中间件。它将仅适用于 /contact/* 路由。
    • hii Jeremy ,我仍然得到这个错误OPTIONS https://localhost:3000/contact/send 0 () 你知道这个错误吗?
    • cors npm 文档中的这一部分应该会有所帮助。 npmjs.com/package/cors#enabling-cors-pre-flight
    • 注意:这在之前的回答中已经说明
    • 谢谢我很累,我会尝试别的方法,解决了这个问题,但得到了其他错误:( OPTIONS localhost:3000/contact/send 0 ()
    猜你喜欢
    • 2018-10-31
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2016-08-17
    相关资源
    最近更新 更多