简体   繁体   English

如何与 Cloudfront 和 ec2 节点服务器通信?

[英]How can I communicate with Cloudfront and the ec2 node server?

using stack使用堆栈

Client: React, Redux, axios Client: React,Redux,axios

Server: AWS-EC2, Route 53, S3, CloudFront, NodeJS, express Server: AWS-EC2、Route 53、S3、CloudFront、NodeJS、express

First, I bought a domain from route53.(ACM certificate issuance completed)首先,我从route53购买了一个域名。(ACM证书颁发完成)

Second, I registered the build file in the bucket as a static website in S3.其次,我将存储桶中的构建文件注册为 S3 中的 static 网站。

Third, linked the Route 53 and S3 bucket to CloudFront.第三,将 Route 53 和 S3 存储桶链接到 CloudFront。

Fourth, EC2 set ELB and EIP.四、 EC2设置ELB和EIP。

Fifth, ec2 contains node.js epxress server.五、 ec2包含node.js个epxress服务器。

Sixth, CloudFront, Redirect from S3 ( www.domain.link => domain.link) was set to第六, CloudFront,从 S3 重定向( www.domain.link => domain.link)设置为

The code of the problematic Client and Server is as follows.有问题的Client和Server的代码如下。

Client.js客户端.js

import axios from "axios";
import { TYPES, MAF } from "./types";
const API_AUTH = "https://www.domain.link/auth";
const API_USER = "https://www.domain.link";
//필수!!
axios.defaults.withCredentials = true;

export function loggedIn(data) {
  return (dispatch) => {
    axios.post(`${API_AUTH}/login`, data).then((res) => {
      console.log(res);
      dispatch({
        type: TYPES.LOGIN_SUCCESS,
        // payload: res.data.userData,
      });

      dispatch({
        type: MAF.HIDE_MODAL,
      });
    });
  };
}

export function register(data) {
  return (dispatch) => {
    axios.post(`${API_AUTH}/register`, data).then((res) => {
      dispatch({
        type: TYPES.REGISTER_SUCCESS,
        payload: res.data,
      });
    });
  };
}

server.js服务器.js

./routes/user.js

const router = require("express").Router();

const {
  login,
  register,
  logout,
  profile,
} = require("../controller/userController/userController");
const { authorization } = require("../config/JWTConfig");

router.post("/auth/login", login);
router.post("/auth/register", register);
router.get("/auth/logout", authorization, logout);
router.get("/auth/profile", authorization, profile);

module.exports = router;

./app.js

const express = require("express");
// const passportConfig = require("./passport/index");
const passport = require("passport");
const http = require("http");
const https = require("https");
const path = require("path");
const fs = require("fs");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const logger = require("morgan");

require("dotenv").config();
const authRoute = require("./routes/users");
const mainRoute = require("./routes/main");
const port = process.env.PORT || 3000;
const app = express();

const whitelist = [
  "http://localhost:3000",
  "http://*.doamin.link",
  "http://doamin.link",
  "http://doamin.link/*",
];
const corsOption = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error("Not allowed by CORS"));
    }
  },
  credentials: true,
  methods: ["GET", "POST", "PUT", "DELETE", "OPTION"],
};

app.use(cookieParser());

app.use(logger("dev"));

app.use(cors(corsOption));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

app.use(mainRoute);
app.use(authRoute);

let server;

if (fs.existsSync("./cert/key.pem") && fs.existsSync("./cert/cert.pem")) {
  const privateKey = fs.readFileSync(__dirname + "/cert/key.pem", "utf8");
  const certificate = fs.readFileSync(__dirname + "/cert/cert.pem", "utf8");
  const credentials = { key: privateKey, cert: certificate };

  server = https.createServer(credentials, app);
  server.listen(port, () => console.log("https server Running"));
} else {
  server = app.listen(port, () => {
    console.log(`http server Running`);
  });
}

module.exports = server;

When I click the Postman or browser login button, this error occurs.当我点击 Postman 或浏览器登录按钮时,出现此错误。

Access to XMLHttpRequest at 'https://www.domain.link/login' 
from origin 'https://domain.link' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check:
 No 'Access-Control-Allow-Origin' header is present on the requested resource.
createError.js:16 Uncaught (in promise) Error: Network Error
    at e.exports (createError.js:16)
    at XMLHttpRequest.p.onerror (xhr.js:84)

domain.link or www.domain.link or the above error occurs. domain.link 或www.domain.link或出现上述错误。

Postman

在此处输入图像描述

How do I get CloudFront + S3 to communicate with EC2?如何让 CloudFront + S3 与 EC2 通信?

in your browser or postman在您的浏览器或 postman

www.domain.link After connecting to domain.link www.domain.link连接到 domain.link 后

When you make a login button or post request当您创建登录按钮或发布请求时

I hope it works well.我希望它运作良好。

If something is missing, please let me know what is missing.如果缺少什么,请告诉我缺少什么。 I will add more.我会添加更多。

You specify allowed methods for CloudFront in your cache behavior.您在缓存行为中为 CloudFront 指定允许的方法 By default only GET and HEAD are allowed:默认情况下只允许 GET 和 HEAD:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM