简体   繁体   English

快速路由器端点的 CORS 问题

[英]CORS issue with Express Router end points

I have a react app that is making a REST to a an express node server.我有一个反应应用程序正在将 REST 制作为快速节点服务器。

The express router defines a bunch of rest endpoints.快速路由器定义了一堆 rest 端点。

When I hit the endpoints in the express router using postman, it works fine.当我使用 postman 访问快速路由器中的端点时,它工作正常。

When I hit the endpoint with me react app, it doesn't.当我用我的反应应用程序到达端点时,它没有。 I'm seeing 400 error when my react app makes the call using axios.当我的反应应用程序使用 axios 拨打电话时,我看到 400 错误。

This is what my index.js looks like:这就是我的 index.js 的样子:

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const cors = require("cors");

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
// server.use(bodyParser.json());
app.use(cors());
// app.options("*", cors());

const UserModel = require("./models/User");

mongoose
  .connect(
    "mongodb"
  )
  .then(() => console.log("SUCESSFULLY connected to MongoDB!"))
  .catch((error) => console.log(`FAILED tot connect to MongoDB: ${error}`));

require("./auth/localStrategyAuth");

const authRoutes = require("./routes/authRoutes");
app.use("/v1", authRoutes);

// app.post("/", (req, res) => {
//   res.send("Hello World!");
// });
// app.post("/v1/signup", (req, res) => {
//   console.log("lol");
// });

// app.use(express.json());
const PORT = 5000;
app.listen(PORT, () =>
  console.log(`ui-rest listening on port localhost:${PORT}`)
);

user.js用户.js

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const { Schema } = mongoose;

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
});

const UserModel = mongoose.model("user", UserSchema);
module.exports = UserModel;

authRoutes.js authRoutes.js

const express = require("express");
const passport = require("passport");
const jwt = require("jsonwebtoken");
const JWTstrategy = require("passport-jwt").Strategy;
//We use this to extract the JWT sent by the user
const ExtractJWT = require("passport-jwt").ExtractJwt;

const router = express.Router();

// When the user sends a post request to this route, passport authenticates the user based on the
// middleware created previously
router.post(
  "/signup",
  passport.authenticate("signup", { session: false }),
  async (req, res, next) => {
    res.json({
      message: "Signup successful",
      user: req.user,
    });
  }

module.exports = router;

localStrategyAuth.js localStrategyAuth.js

const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const UserModel = require("../models/User");

//Create a passport middleware to handle user registration
passport.use(
  "signup",
  new localStrategy(
    {
      usernameField: "email",
      passwordField: "password",
    },
    async (email, password, done) => {
      try {
        // Save the information provided by the user to the the database
        const user = await UserModel.create({ email, password });
        // Send the user information to the next middleware
        return done(null, user);
      } catch (error) {
        done(error);
      }
    }
  )
);

This is what my express router looks like:这是我的快速路由器的样子:

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

router.post(
  "/signup",
  passport.authenticate("signup", { session: false }),
  async (req, res, next) => {
    res.json({
      message: "Signup successful",
      user: req.user,
    });
  }
);

module.exports = router;

What am I missing?我错过了什么? I've set up CORS in the index.js file.我在 index.js 文件中设置了 CORS 。 I just can't see where I'm going wrong.我只是看不出我哪里错了。 Why cant my react app hit the express router endpoints.为什么我的反应应用程序不能访问快速路由器端点。

If I have a normal express endpoint, then my react app is able to hit those endpoints.如果我有一个普通的 express 端点,那么我的 react 应用程序就能够访问这些端点。 For example, the endpoint below works fine when my react app hits it.例如,当我的反应应用程序点击它时,下面的端点工作正常。

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

app.post("/", (req, res) => {
  res.send("Hello World!");
});

const PORT = 5000;
app.listen(PORT, () =>
  console.log(`listening on port localhost:${PORT}`)

app.post("/someSignup", (req, res) => {
   console.log("signup");
 });

I've also tried things like with no luck:我也尝试过没有运气的事情:

const authRoutes = require("./routes/authRoutes");
authRoutes.use(cors());

Here is what my react code looks like when it submits the rest call:这是我的反应代码在提交 rest 调用时的样子:

  // axios setup
axios.create({
  baseURL: "http://localhost:5000",
  // headers: {
  //   "Content-Type": "application/json",
  // },
});

  // Handle submit
  handleSubmit = async (event) => {
    event.preventDefault();
    const newUserData = {
      // firstName: this.state.firstName,
      // lastName: this.state.lastName,
      email: this.state.email,
      password: this.state.password,
    };
    const result = await axios.post("/v1/signup", newUserData);
    console.log(result);
  };

Here is a screenshot of headers tab on chrome console这是 chrome 控制台上的 headers 选项卡的屏幕截图在此处输入图像描述

Here is a screenshot of response tab on chrome console这是 chrome 控制台上的响应选项卡的屏幕截图在此处输入图像描述

Here is a screenshot of the request这是请求的屏幕截图在此处输入图像描述

400 means bad request, your problem isn't about with cors. 400 表示请求错误,您的问题与 cors 无关。 You didn't setup your api to handle JSON data which react sends, so it can't read your request.body and gives 400-Bad Request.您没有设置 api 来处理响应发送的 JSON 数据,因此它无法读取您的 request.body 并给出 400-Bad Request。

So you need to add this line:所以你需要添加这一行:

app.use(bodyParser.json());

Also in the current versions of express, body parser isn't required, it comes with express.同样在当前版本的 express 中,body 解析器不是必需的,它带有 express。 So you can use it like this:所以你可以像这样使用它:

app.use(express.json());

The reason it worked with postman is that you sent the data in x-www-form-urlencoded.它与 postman 一起使用的原因是您以 x-www-form-urlencoded 格式发送数据。

在此处输入图像描述

you can use check my code for cors error.您可以使用检查我的代码来检查 cors 错误。

const express = require('express');
var mongoose = require('mongoose');
const bodyParser = require('body-parser');
var morgan = require('morgan');
var cors = require('cors')
const app = express();

// CORS Middleware
app.use(cors());
// Logger Middleware
app.use(morgan('dev'));
// Bodyparser Middleware
app.use(bodyParser.json());


const MongoClient = require('mongodb').MongoClient;
const uri = "uri";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  console.log('MongoDB Connected...')
  const collection = client.db("dbname").collection("collectionname");

  app.post('/name', (req, res) => {
    collection. insertOne({ name: req.body.name })
    res.send("data added")
  });

});

const port = process.env.PORT || 5000;

app.listen(port, function () {
  console.log(`Example app listening on port ${port}`);
});

You need to register the cors middleware into express app.您需要将 cors 中间件注册到 express 应用程序中。

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();

app.use(cors());

app.post("/", (req, res) => {
  res.send("Hello World!");
});

const PORT = 5000;
app.listen(PORT, () => console.log(`listening on port localhost:${PORT}`)

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

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