Angular 6和Node.js:所请求的资源上没有'Access-Control-Allow-Origin'标头 [英] Angular 6 and Nodejs: No 'Access-Control-Allow-Origin' header is present on the requested resource

查看:61
本文介绍了Angular 6和Node.js:所请求的资源上没有'Access-Control-Allow-Origin'标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在angular 6应用程序和nodejs中都有表单,提交表单时出现以下错误:

I have form in angular 6 app and nodejs, when I submit the form I get the following error:

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. 我搜索并检查了其他类似的错误,但无法摆脱错误:(

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. I searched and checked other similar errors but I could not manage to get rid of the error :(

这是server.js

Here is 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);
      });

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

and here is the routes (contact.js for node mailer)

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并尝试了其他方法,但是什么也没有.

Note: i have installed cors via npm and tried other method but nothing .

我的代码中缺少什么?

推荐答案

修复

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

Fix

Just ensure cors preflight is enabled with options and is header enabled before the call:

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

这篇关于Angular 6和Node.js:所请求的资源上没有'Access-Control-Allow-Origin'标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆