【问题标题】:Having trouble posting to express backend with Axios w/ React使用带有 React 的 Axios 发布到 Express 后端时遇到问题
【发布时间】:2020-04-28 07:18:35
【问题描述】:

我正在使用 React 和 Nextjs,并在端口 3001 上运行 Express 后端。

我正在尝试让我的注册页面将信息发布到数据库, 但我遇到了一组错误

编辑 - 已修复 CORS 问题,发布到 DB 时仍有问题

编辑 - 这是新错误:

POST http://localhost:3001/users/signup 404 (Not Found)

这个未捕获的承诺错误:

createError.js:16 Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)

我认为问题出在 axios 帖子上,但我不确定。 因为我已经启用了 Cors,并且在 axios 选项的标题中也启用了,所以我不确定问题是什么..

后端:

app.js:

const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const session = require("express-session");
const FileStore = require("session-file-store")(session);
const upload = require("express-fileupload");

app.use(upload());
console.log("Server Started!");

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use(logger("dev"));
app.use(cors);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
  session({
    resave: false,
    secret: "hello",
    saveUninitialized: true,
    is_logged_in: false,
  })
);

const indexRouter = require("./routes/index");
app.use("/", indexRouter);

app.get('/', function (req, res) {
  res.send('<h1>hello world</h1>')
});

module.exports = app;

我不确定后端还需要什么,所有路由和东西都由 nextjs 处理。 前端:

SignUp.jsx:

import React from "react";
import { Component } from "react";
import styled from "styled-components";
import {signup} from "./userFunctions";

class Signup extends Component {
  constructor() {
    super();
    this.state = {
      username: "",
      email: "",
      password: "",
      query: "",
      hits: [],
    };
    this.onChangeUsername = this.onChangeUsername.bind(this);
    this.onChangeEmail = this.onChangeEmail.bind(this);
    this.onChangePassword = this.onChangePassword.bind(this);
    this.onChangeQuery = this.onChangeQuery.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeUsername = (e) => {
    this.setState({
      username: e.target.value,
    });
  };

  onChangeEmail = (e) => {
    this.setState({
      email: e.target.value,
    });
  };

  onChangePassword = (e) => {
    this.setState({
      password: e.target.value,
    });
  };

  onChangeQuery = (e) => {
    this.setState({
      query: e.target.value,
    });
  };

  onSubmit = (e) => {
    e.preventDefault();
    console.log("hello")

    const newUser = {
      username: this.state.username,
      email: this.state.email,
      password: this.state.password,
      query: this.state.query
    };


    signup(newUser).then((res) => {
      res.redirect("/chat");
    });
  };

  render() {
    return (
      <Wrapper>
        <TitleWrapper>
          <SignUpTitle>Signup</SignUpTitle>
        </TitleWrapper>
        <FormWrapper>
          <form onSubmit={this.onSubmit}>
          <HThree>E-mail:</HThree>
          <EmailInput
            type="text"
            placeholder="E-mail"
            onChange={this.onChangeEmail}
            value={this.state.email}
          ></EmailInput>
          <HThree>Username:</HThree>
          <UsernameInput
            type="text"
            placeholder="Username"
            onChange={this.onChangeUsername}
            value={this.state.username}
          ></UsernameInput>
          <br></br>
          <HThree>Password:</HThree>
          <PasswordInput
            type="text"
            placeholder="Password"
            onChange={this.onChangePassword}
            value={this.state.password}
          ></PasswordInput>
          <br></br>
          <HThree>Confirm Password:</HThree>
          <PasswordMatchInput
            type="text"
            placeholder="Password-Confirm"
            onChange={this.onChangePassword}
            value={this.state.password}
          ></PasswordMatchInput>
          <br></br>
          <SignUpButton
            type="submit"
            value="Signup"
            className="signup-button"
          ></SignUpButton>
          </form>
          <br></br>
          <LoginPage href="/login">Looking for login?</LoginPage>
        </FormWrapper>
      </Wrapper>
    );
  }
}

这是帖子

userFunctions.js:

import axios from "axios";



const options = {
    credentials: "include",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT"
    },

};

export const signup = (newUser) => {
    return axios
        .post("http://localhost:3001/users/signup", {
            name: newUser.name,
            email: newUser.email,
            password: newUser.password
        }, options)



.then(response => {
        console.log("User is now registered")
    })

}

【问题讨论】:

  • 在您的axios.post 中,将http:// 添加到网址。
  • 更新帖子以立即解决问题
  • 我们需要查看routes/index.js,处理请求的路由。 (并且您可以删除 SignUp.jsx)

标签: javascript node.js reactjs axios next.js


【解决方案1】:

cors 是一个工厂函数,调用它时会返回 Express 中间件函数,该函数设置允许传入的跨源请求所需的 CORS 标头。

app.use(cors()); // instead of app.use(cors)

Link to Documentation

同样在axios 中,您必须在端点 URL 前加上协议部分。

.post("http://localhost:3001/users/signup") // you were missing "http://"

【讨论】:

  • 删除您的自定义 CORS 中间件(实际使用 cors 模块之前的代码)并应用我的更改。它应该工作。无论如何,您都错过了Access-Control-Allow-Credentials,这就是您的请求失败的原因。
  • 改成你说的,什么都没变,还是一样的错误。
  • 删除了我的第一条评论,因为我误读了您所说的内容,但后来我又按照您所说的去做并删除了自定义标题。
  • 我还发现另一个错误 - 您的 POST URL 不正确,因为它不包含协议部分。
  • 您的网址:localhost:3001/users/signup,预期网址:http://localhost:3001/users/signup。缺少的部分是“http://”,它向浏览器表明请求正在使用 HTTP 协议。
猜你喜欢
  • 1970-01-01
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 2019-08-14
  • 2020-02-13
  • 2021-02-26
  • 2020-10-17
相关资源
最近更新 更多