gpt4 book ai didi

node.js - 从 Axios/React 将 json POST 到 Node/Express 服务器时出现问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:23 24 4
gpt4 key购买 nike

我目前正在开发一个 Web 应用程序,使用 Node.js,后端使用 Express,前端使用 React.js。在尝试通过 axios 将用户数据发布到 Node 服务器时,我遇到了问题。当我使用 x-www-form-urlencoded 内容类型发布帖子时,前端将发布到服务器,但发布数据的整个 JSON 出现在第一个元素的关键字段中。当我将内容类型更改为 json 时,它会停止从前端发布任何内容。我尝试过 cUrling 到服务器,并且 curling JSON 帖子将被服务器接受。

react 代码发布到服务器

handleSubmit()
{
var form=this;
var axiosConfig = {
headers: {
'content-type': 'application/json; charset=utf-8'
}
}

axios.post('http://localhost:8080/api/login/', {
'username': form.state.username,
'password': form.state.password
}, {headers: {'content-type': 'application/json'}});

};

api端点的服务器代码

//From server.js
const express=require('express');
const session=require('express-session');
const bodyParser=require("body-parser");
const path = require('path');

var login = require('./routers/login')

var port = process.env.PORT || 8080;
var app=express();

app.use(session({'secret': 'thealphabetbackwardsiszyxwvutsrqponmlkjihgfedcba'}));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

//...

app.use('/api/login', login);

//from login.js
/* Router for login system
When user attempts to log in, check their credentials
If the user successfully logs in, create a session
If user enters invalid credentials prompt them
*/

const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const user = require("./../models/UserSchema")
mongoose.connect('mongodb://localhost/newt');

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

router.get('/', function (req, res)
{
console.log("Test");
})

router.post('/', function(req, res)
{
console.log(req.body);
res.end();
})

// To create test user use path localhost:8080/api/login/testing
router.get('/test', function (req, res)
{
var db = mongoose.connection;

var test = new user({
username: "joesephschomseph",
email: "testUser@test.com",
fname: "Joe",
lname: "Schmoe"
})

test.save();

console.log("Created test user!");
});


module.exports = router

最佳答案

  1. npm install --save const body-parser
  2. 在 app.js 中包含 const bodyparser = require('body-parser');
  3. app.use(bodyparser.urlencoded({ extended: false }));
    app.use(bodyparser.json());
  4. 删除“用户名”和“密码”中的单引号

  5. console.log(req.body);

关于node.js - 从 Axios/React 将 json POST 到 Node/Express 服务器时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com