OPTIONS net :: ERR_CONNECTION_REFUSED +相同源策略不允许读取远程资源(原因:CORS请求未成功)

问题描述 投票:0回答:2

[我在React JS应用程序中使用Nodemailer来获取联系表单数据并将其发送到我的邮件,在我的本地计算机上一切正常,我将应用程序部署到heroku,并且一个测试我的应用程序的朋友注意到了我的表单未提交,当然是已提交并已发送到我的消息框。

清除历史记录和缓存后,我在Chrome上打开了我的应用,并在控制台中注意到此错误:

xhr.js:166 OPTIONS http://localhost:5000/send net::ERR_CONNECTION_REFUSED
createError.js:17 Uncaught (in promise) Error: Network Error
    at e.exports (createError.js:17)
    at XMLHttpRequest.p.onerror (xhr.js:80)

这是Firefox上的错误消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/send. (Reason: CORS request did not succeed).

[请帮我解决这个问题,我将不胜感激,我已经花了几天的时间,查看了资源以及与Stackoverflow相关的所有问题,但是这些问题在我的情况下都无效。

这是我的Axios提取函数调用:

const handleFormSubmit = e => {
    const name = nameRef.current.value, email = emailRef.current.value,
        message = messageRef.current.value;

    e.preventDefault();
    axios({
        url: 'http://localhost:5000/send',
        method: "POST",
        data: {
            name,
            email,
            message
        }
    }).then(({data}) => {
        if (data.msg === 'success') {
            createNotification('Message received, thank you.');
            setClearForm(true);
            setTimeout(() => {setClearForm(false)})
        } else if (data.msg === 'fail') {
            console.log(data);
            createNotification(`Hmm... Something went wrong!`);
        }
    })
};

这是我的服务器代码段:

const express = require('express');
const cors = require('cors');
const path = require('path');
const nodeMailer = require('nodemailer');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

if (process.env.NODE_ENV !== 'production') require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(cors());
app.get('http://localhost:5000/send', function (req, res, next) {
    res.json({msg: 'This is CORS-enabled for all origins!'})
});

if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, 'client/build')));

    app.get('*', function (req, res) {
        res.sendFile(path.join(__dirname, 'client/build', 'index.html'))
    })
}

app.listen(port, err => {
    if (err) throw err;
    console.log(`Server running on port ${port}`)
});

app.post('/send', (req, res) => {
    let name = req.body.name;
    let email = req.body.email;
    let subject = `Message from ${name}, through CodeSurge`;
    let message = req.body.message;
    let content = `name: ${name} \n email: ${email} \n message: ${message} `;

    let transporter = nodeMailer.createTransport({
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            user: process.env.USER,
            pass: process.env.PASS
        }
    });

    let mail = {
        from: name,
        to: '[email protected]',
        subject: subject,
        text: content
    };

    transporter.sendMail(mail, (err, data) => {
        if (err) {
            console.log(err);
            res.json({
                msg: 'fail',
                err
            })
        } else {
            res.json({
                msg: 'success'
            })
        }
    });
});

[如果需要,这是我在Heroku上的应用地址:CodeSurge

我肯定会感谢每个人的专业知识和知识,因为我已经在这里呆了几天了,试图自己解决这个问题。

javascript node.js reactjs cors nodemailer
2个回答
0
投票

问题是您尝试向本地服务器(http://localhost:5000/send)发出http请求。相反,如果您使用的是代理,则需要指向实际的服务器,或者是完整URL还是相对路径。


0
投票

[经过大量查找,对Google代码进行谷歌搜索和重新编辑后,我终于使它工作了,我所做的就是有条件地将url传递给我的axios提取请求,如下所示:

// Form submit handler
    const handleFormSubmit = e => {
        let url;
        process.env.NODE_ENV === 'production' ?  url = `https://codesurge.herokuapp.com/send`
            : url = "http://localhost:5000/send";
        const name = nameRef.current.value, email = emailRef.current.value,
            message = messageRef.current.value;

        e.preventDefault();
        axios({
            url: url,
            method: "POST",
            data: {
                name,
                email,
                message
            }
        }).then(({data}) => {
            if (data.msg === 'success') {
                createNotification('Message received, thank you.');
                setClearForm(true);
            } else if (data.msg === 'fail') {
                createNotification(`Hmm... Something went wrong!`);
            }
        })
    };

之后,在Config Vars部分的Heroku的“我的应用程序设置”选项卡下添加了我的Gmail用户名和密码,这对我来说很神奇。

NOTE:如果您使用Gmail作为邮件提供商,则必须通过在此处启用此功能来远程访问您的邮件:https://accounts.google.com/b/0/DisplayUnlockCaptcha

感谢所有为此添加输入的人。

© www.soinside.com 2019 - 2024. All rights reserved.