我正在尝试使用axios将数组从react发送到我的Node.js文件,但是我的状态为404 error
。
我的profileSchema如下:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
preference: [
{
type: String
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
我想使用axios request
将数组发送到后端。
例如
tempArray=["Chocoloate","Vanilla","Strawberry"]
我发出的axios请求是
axios
.post('/api/profile/register', tempArray)
.then(res => console.log(res.data))
.catch(err => console.log(err));
我的profile.js
外观将其列出。我还安装了body-parse并全部安装了。
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const passport = require("passport");
const Profile = require("../../models/Profile");
// Load User Model
const User = require("../../models/User");
router.get("/test", (req, res) => res.json({ msg: "Profile Works" }));
// @route POST api/profile
// @desc Create or edit user profile
// @access Private
router.post(
"/register",
(req, res) => {
console.log(req);
var list = req.body;
console.log(list);
}
);
但是,我仍然遇到404错误,无法将数组保存到后端
index.js文件
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const posts = require("./routes/api/posts");
const issues = require("./routes/api/issues");
const mp = require("./routes/api/mp");
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport Config
require("./config/passport")(passport);
// Use Routes
app.use("/api/users", users);
app.use('/api/profile', profile);
app.use("/api/posts", posts);
app.use("/api/issues", issues);
app.use("/api/mp", mp);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
答案 0 :(得分:0)
始终尝试将帖子正文作为对象发送。
tempArray = ['a', 'b', 'c']
axios
.post('/api/profile/register', {tempArray: tempArray})
.then(res => console.log(res.data))
.catch(err => console.log(err));
,router.post中的主体参数为
router.post('/register/', function(req, res,next) {
const tempArray = req.body.tempArray;
//perform your query operations here and pass tempArray as params to your query
})