Reputation: 251
I am using React, and Nextjs with a Express back-end running on port 3001.
I am trying to get my sign up page to post the info to the database, but I am getting a set of errors
EDIT - FIXED CORS ISSUE, Still having issues posting to DB
EDIT - THIS IS THE NEW ERROR:
POST http://localhost:3001/users/signup 404 (Not Found)
This Uncaught promise error:
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
I thought the issue was with the axios post, but I am not sure. Because I already have Cors enabled, and in the headers for axios options too, I am not sure what the issue is..
BACKEND :
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;
I am not sure what else you would need out of the backend, all routes and stuff are handled with nextjs. FRONTEND:
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>
);
}
}
Here is the post statements
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")
})
}
Upvotes: 0
Views: 330
Reputation: 8856
cors
is a factory function which when called returns the Express middleware function which sets the required CORS headers which allow incoming cross origin requests.
app.use(cors()); // instead of app.use(cors)
Also in axios
you must prefix your endpoint URL with the protocol part.
.post("http://localhost:3001/users/signup") // you were missing "http://"
Upvotes: 2