每次尝试发布时,我都会收到无法获取/ api / auth / signup的错误,我无法弄清楚为什么 有人可以帮助我吗?非常感谢,我不明白我想在节点js中发布寄存器的过程,但是它总是告诉我无法获取/ api / auth / signup
auth.js
import axios from "axios";
const API_URL = "http://localhost:8080/api/auth/";
class AuthService {
async login(username, password) {
console.log(username, password);
return axios
.post(API_URL + "signin", {
username,
password,
})
.then((response) => {
if (response.data.accessToken) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
});
}
async logout() {
localStorage.removeItem("user");
}
async register(username, email, password) {
return axios.post(API_URL + "signup", {
username,
email,
password,
});
}
getCurrentUser() {
return JSON.parse(localStorage.getItem("user"));
}
}
export default new AuthService();
server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8080",
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "it works." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
答案 0 :(得分:0)
似乎您正在尝试过帐到不存在的路由。您需要构建/api/auth/signup
路由,以便从axios向其发送请求。
// simple example of post route
app.post("/api/auth/signup", (req, res) => {
const { username, email, password } = req.body;
// Your logic to register user in your database
// Send response after database interaction
res.status(201).json({ message: 'User signed up for service' })
});
答案 1 :(得分:0)
对于每个特定路由,您需要在应用程序中实现相应的路由。 在您的应用程序中,如果您需要访问两个不同URL的发布请求,则需要处理两个发布路由。
For`/api/auth/signin`
app.post('/api/auth/signin', (req, res)=>{
//Your Implementation here
res.status(201).json({message: 'Your Message'})
})
For`/api/auth/signup`
app.post('/api/auth/signup', (req, res)=>{
//Your Implementation here
res.status(201).json({message: 'Your Message'})
})