Express JS 服务器不允许从已部署的应用发布



当部署我的应用程序与h-pages时,我有服务器问题。当我尝试POST/contact url时,它响应405方法不允许。我试过用cors在express上,但它是一样的。我的客户端是React。当我在本地主机上运行它时,一切工作正常,但在生产中,服务器不存在。我应该在我的react应用中添加一些东西来连接它们还是…?

const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path')
const nodemailer = require('nodemailer');
const cors = require('cors')
const pass = require('./.vscode/settings.json')
const config = require('./config')
var allowedOrigins = ['http://localhost:3000','https://some.github.io'];
const corsOptions = {
origin: function(origin, callback){    
if(!origin) return callback(null, true);    
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}   
return callback(null, true);
},
credentials: true,
}
const app = express();
const route = express.Router();
app.use(express.static(path.join(__dirname, 'client' ,'/public')))
app.use(cors(corsOptions))
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'https://some.github.io');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', route)
http.createServer(app).listen(config.port, () => {
console.log(`Listening on port ${config.port}`)
});
app.get('/', (req, res) => {
console.log('server')
res.sendFile(path.join(__dirname, 'client' ,'/public', 'index.html'));
});
const transporter = nodemailer.createTransport({
port: 465,              
host: "smtp.gmail.com",
auth: {
user: 'email',
pass: pass,
},
secure: true,
});
route.get('/contact', (req,res) => {
res.status(200).send('Contact page')
})
route.post('/contact', (req, res) => {
const {name, email, message} = req.body
console.log(req.body)
const mailToMe = {
from: 'email',  // sender address
to: 'email',   // list of receivers
subject: name,
text: message,
html: message + `<br> From: ${email}`,
};
transporter.sendMail(mailToMe, (error, info) => {
if(error) {
return console.log(error)
}
res.redirect('/contact')
res.status(200)
});
})

这是react中的客户端组件:

const ContactForm = () => {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [message, setMessage] = useState('')
const [errorName, setErrorName] = useState('')
const [errorEmail, setErrorEmail] = useState('')
const [errorMessage, setErrorMessage] = useState('')
const [isSubmited, setIsSubmited] = useState(false)
useEffect(() => {
if(isSubmited){
setTimeout(() => {
setIsSubmited(false)
}, 7000)
}
})
const handelValidation = () => {
setErrorName('')
setErrorEmail('')
setErrorMessage('')
// Name
if (!name) {
setErrorName("Name field cannot be empty!")
return false
}
if (!name.match(/[A-Z][a-z]+ [A-Z][a-z]+/)) {
setErrorName("Тhe first and second names must begin with a capital letter and continue with lowercase letters!")
return false
}
// Email
if (email === '') {
setErrorEmail("Email field cannot be empty!")
return false
}
if (!email.match(/[A-Za-z0-9.]+@[a-z]+.[a-z]+.?[a-z]+/)) {
setErrorEmail("Email must be valid!")
return false
}
// Message
if (message === '') {
setErrorMessage("Message field cannot be empty!")
return false
}

if(message.length <= 10) {
setErrorMessage("Message should more the 10 characters!")
return false
}
return true
}
const handleSubmit = (e) => {
e.preventDefault()
let result = handelValidation();
console.log(name, email, message)
if (!result) {
return
}
let data = { name: name, email: email, message: message }
axios.post(`/contact`, data).catch(e => console.log(e))
setName('')
setEmail('')
setMessage('')
setIsSubmited(true)
}
return (
<Form onSubmit={handleSubmit}>
<Input
onChange={e => setName(e.target.value)}
label={"What is your name?"}
name={"name"}
icon={"far fa-user"}
placeholder={"Type your first and second name..."}
value={name}
isError={errorName}
/>
{errorName ? <Notification error={errorName} /> : ""}
<Input
onChange={e => setEmail(e.target.value)}
label={"Write your email"}
name={"email"}
icon={"far fa-envelope"}
placeholder={"Type your email..."}
value={email}
isError={errorEmail}
/>
{errorEmail ? <Notification error={errorEmail} /> : ""}
<Input
onChange={e => setMessage(e.target.value)}
label={"What is your message to me?"}
name={"message"}
icon={"far fa-comment-alt"}
placeholder={"Type your message..."}
value={message}
isError={errorMessage}
/>
{errorMessage ? <Notification error={errorMessage} /> : ""}
<SubmitButton title={"Submit form"} />
{isSubmited ? <Div>Thank you for contacting me! You must have received an automatic reply 
to the email you entered above.</Div> : ""}
</Form>
)
}

Github Pages不支持任何类型的服务器端编程。

你需要托管(有许多云服务,将让你部署一个Node.js web服务,以及vps和专用服务器,你可以租用),你可以运行你的服务器端JavaScript。你不能只是把它放到Github页面上,让它做任何事情。

您需要部署公共服务器而不是本地服务器。本地服务器只有你可以访问,其他人不能。

最新更新