【发布时间】:2017-10-20 10:52:38
【问题描述】:
我有一个带有 JQuery 的基本 HTML 网站,它向节点服务器提交 Ajax POST 请求,一切正常在我的机器(Windows)上本地运行,我可以在浏览器中提交表单获取服务器上的请求并发送一个适当的响应但是在我的 VPS (droplet) 上没有任何东西到达 POST 路由。虽然我的 GET '/' 运行良好。
这是我的 app.js
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var express = require('express');
var path = require('path');
var app = express();
var location = path.join(__dirname + '/../src');
var bodyParser = require('body-parser');
var config = require('./config/config.json');
var port = 8080;
var nodemailer = require('nodemailer');
var cors = require('cors');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(location));
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// theTransporter will be used to send mail
var theTransporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // use SSL
auth: {
user: config.auth.user,
pass: config.auth.pass
}
});
// handle post requests for contact form
app.post('/contact', function (req, res) {
// get a copy of the newContact object
var newContact = req.body;
// Construct the email to be sent
var message = "New Email from " + newContact.name + "\n";
message += "Email Address: " + newContact.email + "\n";
message += "Phone Number: " + newContact.phone + "\n";
message += "Company name: " + newContact.companyname + "\n";
message += " Industry: " + newContact.industry + "\n";
message += "Subject: " - newContact.subject + "\n";
message += "Message from " + newContact.name + ": \n";
message += newContact.message;
// setup e-mail data with unicode symbols
var mailOptions = {
from: newContact.email, // sender address
to: config.emailAddress, // reciever address
subject: newContact.email + " - " + newContact.subject, // Subject line
text: message
};
// Check if email is undefined, return complaint to client if so
if (typeof newContact.email === "undefined" || newContact.email == "") {
res.status(200).jsonp({
message: "Error - No Email provided.",
error: true,
error_contents: "No Email Provided",
user_generated: true
});
return;
}
// Check if phone is undefined, return complaint to client if so
if (typeof newContact.phone === "undefined" || newContact.phone == "") {
res.status(200).jsonp({
message: "Error - No Phone Number provided.",
error: true,
error_contents: "No Phone Number Provided",
user_generated: true
});
return;
}
// Check if message is undefined, return complaint to client if so
if (typeof newContact.message === "undefined" || newContact.message == "") {
res.status(200).jsonp({
message: "Error - No Message provided.",
error: true,
error_contents: "No Message Provided",
user_generated: true
});
return;
}
// Check if name is undefined, return complaint to client if so
if (typeof newContact.name === "undefined" || newContact.name == "") {
res.status(200).jsonp({
message: "Error - No Name provided.",
error: true,
error_contents: "No Name Provided",
user_generated: true
});
return;
}
// Check if Company Name is undefined, return complaint to client if so
if (typeof newContact.companyname === "undefined" || newContact.companyname == "") {
res.status(200).jsonp({
message: "Error - No Company Name provided.",
error: true,
error_contents: "No Company Name Provided",
user_generated: true
});
return;
}
// Check if Industry is undefined, return complaint to client if so
if (typeof newContact.industry === "undefined" || newContact.industry == "") {
res.status(200).jsonp({
message: "Error - No Industry provided.",
error: true,
error_contents: "No Industry Provided",
user_generated: true
});
return;
}
// Send the email with Transporter
theTransporter.sendMail(mailOptions, function (err, info) {
if (err) {
// log the error
console.log(err);
// send it back to the client
res.status(500).jsonp({
message: "something went wrong..",
error: true,
error_contents: err,
user_generated: false
});
return;
} else {
// log the good news
console.log('Email sent succesfully to ' + mailOptions.to);
// close transporter
theTransporter.close();
// send a good response back to client
res.status(200).jsonp({
message: "GG",
error: false,
error_contents: null,
user_generated: null
});
return;
}
});
});
// Default catch all for website
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/../src/index.html'));
});
app.listen(port, function () {
console.log(process.env.NODE_ENV + ' server running at http://localhost:' + port);
})
这是我对客户的要求...
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "https://www.localhost.ca:8080/contact",
data: frm.serialize(),
success: function (data) {
if (data.err && data.user_generated) {
$('.output-message').text("Message not sent: " + data.error_contents);
$('.output-message').css("color", "red");
} else if (data.err) {
$('.output-message').text("Internal Server Error - Please try again in a couple of moments");
$('.output-message').css("color", "red");
} else {
$('.output-message').text("Message sent succesfully!");
$('.output-message').css("color", "green");
document.getElementById('contact-form').reset();
}
},
error: function (data) {
if (data.err && data.user_generated) {
$('.output-message').text("Message not sent: " + data.error_contents);
$('.output-message').css("color", "red");
} else if (data.err) {
$('.output-message').text("Internal Server Error - Please try again in a couple of moments");
$('.output-message').css("color", "red");
}
}
});
});
假设是服务器设置导致了问题,我设置了一个新的 Ubuntu Droplet 并安装了节点,我还 [使用此方法][1] 设置了 SSL 证书。如果它也有帮助的话,我可以发布我的 Nginx 配置。除此之外,我真的很难过。我现在已经设置了两个液滴,并且无法在任何一个上进行 POST 工作。显然使用了相同的错误策略。
奇怪的是它在本地运行完美,所以我认为这很好,任何问题或建议将不胜感激!
编辑:
这是我的 NGINX 配置文件
server {
listen 80 default_server;
listen [::]:80 default_server;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/tycoonmedia/src;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name tycoonmedia.ca www.tycoonmedia.ca;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
try_files $uri $uri/ =404;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
# fastcgi_pass unix:/run/php/php7.0-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/tycoonmedia.ca/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/tycoonmedia.ca/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
if ($scheme != "https") {
return 301 https://$host$request_uri;
} # managed by Certbot
# Redirect non-https traffic to https
# if ($scheme != "https") {
# return 301 https://$host$request_uri;
# } # managed by Certbot
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
server {
# listen 80;
# listen [::]:80;
#
# server_name tycoonmedia.ca www.tycoonmedia.ca;
#
# root /var/www/tycoonmedia/src;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
[1]: https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let
-s-encrypt-on-ubuntu-16-04
【问题讨论】:
-
使用 AJAX 错误响应更容易诊断。
-
@Chase 抱歉,我应该注意到响应非常慢,并且出现 net::ERR_CONNECTION_TIMED_OUT 错误。我已经使用 Postman 尝试了各种请求配置,但我得到的最好的结果就是超时。
-
你的帖子还能用吗?
curl -v -X POST -d 'somedata' http://yourserver/your/post/path的结果是什么? -
@I.R.R.我得到一个“永久移动的 Nginx 页面..
-
嗯,然后将其范围缩小到 nginx 配置。发布您的网络服务器配置,并且在 nginx 方面更好的人可能会注意到发生了什么。
标签: jquery node.js ajax express nginx