【问题标题】:Ajax Post with express js get req parameter error带有express js的Ajax Post获取req参数错误
【发布时间】:2020-06-29 16:37:03
【问题描述】:

我正在使用 ajax 从 javascript 前端发布数据以表达 js 有后端服务器。我如何在 express js api 方法 req 参数中获取发布的数据。当我尝试解析以下请求数据时遇到问题是我的代码。请帮我解决这个问题

            $.ajax({
                url: "http://localhost:8080/api/save_user/",
                type: "POST",
                crossDomain: true,
                data: { name: 'Justin', number: '662***' },
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)

                },
                error: function (xhr, status) {
                    alert("error");
                }
            });    


Express Js服务器端

const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())


//deploy the smart contract
app.post('/api/save_user', (req, res) => {
    console.log((JSON.parse(req.body)));
    res.send({})
})

错误日志

SyntaxError: Unexpected token n in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/node_modules/body-parser/lib/types/json.js:158:10)
    at parse (/node_modules/body-parser/lib/types/json.js:83:15)
    at /node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/raw-body/index.js:224:16)

【问题讨论】:

  • log.console(response) 的输出是什么
  • 在路由app.use(express.json({ type: ['application/json', 'text/plain'] })) 之前在express中添加行并重试
  • 我面临问题 console.log((JSON.parse(req.body)));在服务器端 express js

标签: javascript node.js express


【解决方案1】:

问题是 jquery 期望你传递一个带有 json 的字符串。试试这样:

            $.ajax({
                url: "http://localhost:8080/api/save_user/",
                type: "POST",
                crossDomain: true,
                data: JSON.stringify({ name: 'Justin', number: '662***' }),
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)

                },
                error: function (xhr, status) {
                }
            });

【讨论】:

  • 还是一样,我正面临这个问题。
  • 这行得通,但我需要在 express js 服务器端删除 JSON.parse
  • 这一行app.use(bodyParser.json()),解析所有请求和响应。
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-03
  • 2020-11-03
  • 2018-03-08
相关资源
最近更新 更多