- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有带 AXIOS 的完整 MERN 堆栈应用程序。在我的本地主机上,该应用程序运行良好,但是当我在 nginx 上部署该应用程序时,所有 POST 请求 都被拒绝。我尝试了很多在网上找到的解决方案,但没有用。我认为这是 CORS 问题/nginx 配置问题。我让 Nginx.conf 正确吗?我的 Node 在 localhost:8000 上运行,React 在 localhost:3000 上运行。
编辑
我尝试过的事情:
Nginx.conf:
server {
listen 80;
server_name lovechangingtheworld.org;
location / {
proxy_pass http://localhost:8000;
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;
}
}
我在 Node 上也需要这个吗?
router.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header(
"Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
response.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
Node :
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const passport = require("passport");
// Load Input Validation
const validateRegisterInput = require("../../validation/register");
const validateLoginInput = require("../../validation/login");
// Load User model
const User = require("../../models/User");
router.use((request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header(
"Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
response.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
// @route GET api/users/test
// @desc Tests users route
// @access Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));
// @route POST api/users/register
// @desc Register user
// @access Public
router.post("/register", (req, res) => {
console.log("333333333333333333333333", req.body);
const { errors, isValid } = validateRegisterInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({ email: req.body.email }).then(user => {
if (user) {
errors.email = "Email already exists";
return res.status(400).json(errors);
} else {
// const avatar = gravatar.url(req.body.email, {
// s: '200', // Size
// r: 'pg', // Rating
// d: 'mm' // Default
// });
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
});
}
});
});
// @route GET api/users/login
// @desc Login User / Returning JWT Token
// @access Public
router.post("/login", (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
// Check Validation
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
// Find user by email
User.findOne({ email }).then(user => {
// Check for user
if (!user) {
errors.email = "User not found";
return res.status(404).json(errors);
}
// Check Password
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User Matched
const payload = {
id: user.id,
name: user.name,
admin: user.adminLevel
}; // Create JWT Payload
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
errors.password = "Password incorrect";
return res.status(400).json(errors);
}
});
});
});
// @route GET api/users
// @desc Get users
// @access Public
router.get("/", (req, res) => {
User.find({})
.sort({ date: -1 })
.then(users => {
console.log("get", users), res.json(users);
})
.catch(err => res.status(404).json({ nousersfound: "No users found" }));
});
// @route GET api/users/:id
// @desc Get eventful by id
// @access Public
router.get("/:id", (req, res) => {
User.findById(req.params.id)
.then(user => {
console.log(user), res.json(user);
})
.catch(err =>
res.status(404).json({ nouserfound: "No user found with that ID" })
);
});
// @route POST api/users/:id
// @desc change user to admin
// @access Private
router.post(
"/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
User.findOne({ _id: req.params.id })
.then(user => {
console.log("1231231231", user);
if (user) {
if(user.adminLevel)
user.adminLevel = false;
else
user.adminLevel = true;
}
user.save().then(user => res.json(user));
})
.catch(err => res.status(404).json({ usernotfound: "No post found" }));
}
);
// @route GET api/users/current
// @desc Return current user
// @access Private
router.get(
"/current",
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email,
admin: req.user.adminLevel
});
}
);
// @route DELETE api/users
// @desc Delete user
// @access Private
router.delete(
"/",
passport.authenticate("jwt", { session: false }),
(req, res) => {
console.log("at route", req.body);
User.findOneAndRemove({ _id: req.user.id }).then(() =>
res.json({ success: true })
);
}
);
module.exports = router;
最佳答案
你的nginx配置有误。对于要通过 nginx 公开的 Node 应用程序,您需要 Reverse Proxy我已经回答了related question
不使用 SSL 的反向代理的 nginx 配置。服务器。
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
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;
}
}
使用 SSL
server {
listen 443;
server_name example.com;
ssl_certificate /etc/letsencrypt/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/privkey.pem;
ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Fix the “It appears that your reverse proxy set up is broken" error.
proxy_pass http://localhost:3000;
proxy_read_timeout 90s;
proxy_redirect http://localhost:3000 https://example.com;
}
}
在 example.com
中,您将已注册的域与您的 IP 放在一起。如果您没有域,可以通过将其添加到主机中来测试它 How to add an IP to hostname file
例子127.0.0.1 example.com
在你看到 http://localhost:3000;
的地方,你输入了 internal Node 应用程序的 IP 和端口。如果它在同一台机器上,您将其保留为 localhost:port。
编辑 1
在你的情况下
server {
listen 80;
server_name lovechangingworld.org;
location / {
proxy_pass http://localhost:8000;
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;
}
}
编辑 2
要使 nodemailer 工作,有两种方法。假设 nodemailer
在端口 localhost:3000
上运行,要么使用像 lovechangingworld.org:8088< 这样的端口
或创建一个子域,例如 mail.lovechangingworld.org
。在 sites-available
中创建文件 touch mail.lovechangingworld.org
2.添加配置
示例 1 新子域:
server {
listen 80;
server_name mail.lovechangingworld.org;
location / {
proxy_pass http://localhost:3000;
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;
}
}
示例 2 不同的端口:
server {
listen 8088;
server_name lovechangingworld.org;
location / {
proxy_pass http://localhost:3000;
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;
}
}
关于node.js - 无法加载资源 : the server responded with a status of 405 (Not Allowed) needs help on nginx. conf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54068827/
我正在 Angular js和sails.js(node.js框架)之间的cors问题上挣扎 我尝试修复错误:XMLHttpRequest无法加载http://localhost:1337/en/au
我在我的应用程序中动态创建一个 iframe,结果如下所示: 这样的沙箱配置是否安全(特别是允许将 iframe 内容视为来自同一来源)? 最佳答案 正如 Namey 评论的那样,allow-sam
突然,似乎没有更改我的网络应用程序中的任何内容,我在 Chrome 中打开它时开始收到 CORS 错误。我尝试添加 Access-Control-Allow-Origin: *标题。然后我得到这个错误
我正在使用 Ionic Framework 开发应用程序。 在后端,我为 api 编写了一个 Flask 应用程序,如下所示: @API.route("/saverez",methods=["POST
我正在尝试从 onesignal api 发送 POST 请求 代码 axios({ method: 'post', url: 'https://onesignal.com/api/v1/no
我一直在寻找一些类似的问题来寻找答案,但我找不到。我有一个带有 express 的 node.js 服务器: app.use(function(req, res, next) { res.head
我使用 Google Cloud Functions 创建了一个 API 端点,并试图从 JS 获取函数中调用它。 我遇到了我很确定与 CORS 或输出格式有关的错误,但我不确定发生了什么。其他一些
当我尝试从我的 Angular 6 应用程序访问 Webhdfs 时,我收到如下所示的错误。在我看来,我几乎尝试了所有方法,包括更改 core-site.xml 和 hdfs-site.xml 中的设
我刚刚学习 ajax 和 cors 一些东西,现在我想知道 chrome 插件“allow-control-allow-origin”是如何工作的。 当我尝试执行正常的 ajax 请求时,控制台显示错
我正在努力理解如何允许用户在列表中创建新记录,但只允许创建者更新他们自己的帖子。 例如。以下结构: post { post1: { author: "user1"
我们的网络上有 2 个内部(内联网)Windows 服务器,仅适用于本地网络。在 server1 上安装了 Spark,我们可以在其中查询 Jabber 信息,如下所示: http://server1
所以在 routing.yml 中我定义了以下路由,以便编辑和删除特定设置: 路由.yml: settings.editDefaults: path: settings/{id}/d
我哪里出错了 title $.get("http://api.angel.co/1/tags/1654/startups?callback=aaa", function(data
首先,对您可能犯的语法错误表示歉意。我的英语不是很好。 我是 Spring 新手,我正在尝试创建基本身份验证安全性。 我正在尝试配置一个端点具有公共(public)访问权限,而其他端点则具有用户访问权
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: NULL in MySQL (Performance & Storage) 如果出现以下情况,您是否强烈建议取消选中
我正在尝试将我的一个网站中的内容加载到另一个网站中: $('#include-from-outside').load('http://lujanventas.com/plugins/banne
这里出了什么问题? OPTIONS https://twitter.com/oauth/request_token 401 (Unauthorized) jsOAuth-1.3.4.js:483 XM
allow-control-allow-origin : * header 存在于 API 响应中,但浏览器仍显示错误。网络 403 错误。 这是来自 API 的示例响应 header : Acces
在 Go 中制作 slice 时的 capacity 参数对我来说意义不大。例如, aSlice := make([]int, 2, 2) //a new slice with length and
Gitlab 保护分支中“允许推送”和“允许 merge ”是什么意思 最佳答案 引用 Gitlab Documentation here Using the "Allowed to push" an
我是一名优秀的程序员,十分优秀!