无法将 axios post 发送到节点 js 服务器 - net::ERR_CONNECTION_REFUSED 在本地主机上
Not able to send an axios post to a node js server - net::ERR_CONNECTION_REFUSED on localhost
我正在尝试从我的 localhost:3000 上的 react/node/axios 网站和本地主机上的 node/nodemailer 服务器 运行 发送表单:4000,当提交form/axios.post 需要几秒钟然后我在 clg 上收到此错误:
Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError
(xhr.js:84) xhr.js:177 POST http://localhost:4000/send_mail net::ERR_CONNECTION_REFUSED
我在代码和我的机器上尝试了很多东西,比如禁用 firewall/protections... 没有任何效果。
这是我正在使用的 React 组件:
import React from 'react';
import { Link } from 'react-router-dom';
import ReCAPTCHA from 'react-google-recaptcha';
import axios from 'axios';
import './style.css';
const ContactForms = () => {
const [isWork, setIsWork] = React.useState(false);
const [name, setName] = React.useState('');
const [telephone, setTelephone] = React.useState('');
const [email, setEmail] = React.useState('');
const [file, setFile] = React.useState();
const [message, setMessage] = React.useState('');
const [sent, setSent] = React.useState(false);
const [msg, setMsg] = React.useState('');
const recaptchaRef = React.createRef();
console.log(sent);
console.log(name);
const handleSand = async (e) => {
e.preventDefault();
const token = await recaptchaRef.current.executeAsync();
// const formData = new FormData();
// formData.append('name', name);
// formData.append('telephone', telephone);
// formData.append('email', email);
// formData.append('token', token);
// formData.append('file', file);
// formData.append('message', message);
axios
.post('http://localhost:4000/send_mail', {
name,
telephone,
email,
token,
file,
})
.then((r) => {
setSent(true);
setMsg(r.data.message);
})
.catch((e) => {
console.log(e);
});
};
console.log(file);
if (sent) return <div>{msg}</div>;
return (
<>
{!sent ? (
<section className="faleConosco" id="forms">
<div className="faleConosco__background"></div>
<div className="faleConosco__formulario">
<div className="faleConosco__buttons">
<button
className="button--amarelo amarelo"
onClick={() => setIsWork(false)}
>
Fale conosco
</button>
</div>
<div className="faleConosco__info">
<h2 className="faleConosco__title title--style">
Faça parte do nosso time
</h2>
<span className="faleConosco__subtitle">
E transforme a gestão de telecom com a gente
</span>
<form className="formularioContato" onSubmit={handleSand}>
<input
type="text"
placeholder="Nome completo"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<button type="submit" className="button--azul">
Enviar
</button>
<label>
<input type="checkbox" required />
Eu li, estou ciente das condições de tratamento dos meus dados
pessoais e dou meu consentimento, quando aplicável, conforme
descrito nesta política de privacidade
</label>
<ReCAPTCHA
sitekey="6Lf3EpAaAAAAAOaWFeNFGhqaQk0Fab4gMfDclxx0"
size="invisible"
ref={recaptchaRef}
/>
</form>
</div>
</div>
</section>
) : (
<section className="faleConosco" id="forms">
<div className="faleConosco__background"></div>
<div className="faleConosco__formulario">
<h1>enviado</h1>
</div>
</section>
)}
</>
);
};
export default ContactForms;
这是我的服务器代码:
const express = require('express');
const app = express();
require('dotenv').config();
const bodyParser = require('body-parser');
const cors = require('cors');
const nodemailer = require('nodemailer');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
app.post('/send_mail', cors(), async (req, res) => {
let { text } = req.body;
const transport = nodemailer.createTransport({
service: process.env.MAIL_SERVICE,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transport.sendMail({
from: `Leads Tel&Com <${process.env.MAIL_USER}>`,
to: `${process.env.MAIL_USER}`,
subject: 'teste',
text: 'teste',
});
});
app.listen(
(process.env.PORT || 4000,
() => {
console.log('Server is listening on port 4000');
})
);
我注意到您正在使用 cors() 作为中间件,那么您为什么要在后端的 post 路由中再次发送 cors()。对后端的任何请求最终都会通过 app.use(cors()),无需在 post 路由中再次发送 cors。
同时检查您的前端,您很可能遇到了 cors 错误。可能是因为上面提到的问题。
我认为你的后端应用不是 运行,你有额外的括号 app.listen((....))
和 app.listen
旧代码
app.listen(
(process.env.PORT || 4000,
() => {
console.log('Server is listening on port 4000');
})
);
新密码
app.listen(process.env.PORT || 4000, () => {
console.log('Server is listening on port 4000');
});
我正在尝试从我的 localhost:3000 上的 react/node/axios 网站和本地主机上的 node/nodemailer 服务器 运行 发送表单:4000,当提交form/axios.post 需要几秒钟然后我在 clg 上收到此错误:
Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError
(xhr.js:84) xhr.js:177 POST http://localhost:4000/send_mail net::ERR_CONNECTION_REFUSED
我在代码和我的机器上尝试了很多东西,比如禁用 firewall/protections... 没有任何效果。
这是我正在使用的 React 组件:
import React from 'react';
import { Link } from 'react-router-dom';
import ReCAPTCHA from 'react-google-recaptcha';
import axios from 'axios';
import './style.css';
const ContactForms = () => {
const [isWork, setIsWork] = React.useState(false);
const [name, setName] = React.useState('');
const [telephone, setTelephone] = React.useState('');
const [email, setEmail] = React.useState('');
const [file, setFile] = React.useState();
const [message, setMessage] = React.useState('');
const [sent, setSent] = React.useState(false);
const [msg, setMsg] = React.useState('');
const recaptchaRef = React.createRef();
console.log(sent);
console.log(name);
const handleSand = async (e) => {
e.preventDefault();
const token = await recaptchaRef.current.executeAsync();
// const formData = new FormData();
// formData.append('name', name);
// formData.append('telephone', telephone);
// formData.append('email', email);
// formData.append('token', token);
// formData.append('file', file);
// formData.append('message', message);
axios
.post('http://localhost:4000/send_mail', {
name,
telephone,
email,
token,
file,
})
.then((r) => {
setSent(true);
setMsg(r.data.message);
})
.catch((e) => {
console.log(e);
});
};
console.log(file);
if (sent) return <div>{msg}</div>;
return (
<>
{!sent ? (
<section className="faleConosco" id="forms">
<div className="faleConosco__background"></div>
<div className="faleConosco__formulario">
<div className="faleConosco__buttons">
<button
className="button--amarelo amarelo"
onClick={() => setIsWork(false)}
>
Fale conosco
</button>
</div>
<div className="faleConosco__info">
<h2 className="faleConosco__title title--style">
Faça parte do nosso time
</h2>
<span className="faleConosco__subtitle">
E transforme a gestão de telecom com a gente
</span>
<form className="formularioContato" onSubmit={handleSand}>
<input
type="text"
placeholder="Nome completo"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<button type="submit" className="button--azul">
Enviar
</button>
<label>
<input type="checkbox" required />
Eu li, estou ciente das condições de tratamento dos meus dados
pessoais e dou meu consentimento, quando aplicável, conforme
descrito nesta política de privacidade
</label>
<ReCAPTCHA
sitekey="6Lf3EpAaAAAAAOaWFeNFGhqaQk0Fab4gMfDclxx0"
size="invisible"
ref={recaptchaRef}
/>
</form>
</div>
</div>
</section>
) : (
<section className="faleConosco" id="forms">
<div className="faleConosco__background"></div>
<div className="faleConosco__formulario">
<h1>enviado</h1>
</div>
</section>
)}
</>
);
};
export default ContactForms;
这是我的服务器代码:
const express = require('express');
const app = express();
require('dotenv').config();
const bodyParser = require('body-parser');
const cors = require('cors');
const nodemailer = require('nodemailer');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors());
app.post('/send_mail', cors(), async (req, res) => {
let { text } = req.body;
const transport = nodemailer.createTransport({
service: process.env.MAIL_SERVICE,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transport.sendMail({
from: `Leads Tel&Com <${process.env.MAIL_USER}>`,
to: `${process.env.MAIL_USER}`,
subject: 'teste',
text: 'teste',
});
});
app.listen(
(process.env.PORT || 4000,
() => {
console.log('Server is listening on port 4000');
})
);
我注意到您正在使用 cors() 作为中间件,那么您为什么要在后端的 post 路由中再次发送 cors()。对后端的任何请求最终都会通过 app.use(cors()),无需在 post 路由中再次发送 cors。
同时检查您的前端,您很可能遇到了 cors 错误。可能是因为上面提到的问题。
我认为你的后端应用不是 运行,你有额外的括号 app.listen((....))
和 app.listen
旧代码
app.listen(
(process.env.PORT || 4000,
() => {
console.log('Server is listening on port 4000');
})
);
新密码
app.listen(process.env.PORT || 4000, () => {
console.log('Server is listening on port 4000');
});