【问题标题】:Why json-parser parse wrong my json为什么 json-parser 解析错误我的 json
【发布时间】:2018-06-13 17:15:33
【问题描述】:

我正在使用 node.js 为服务器端和 angular 前端部分做一个应用程序。我在使用简单的 post 方法时遇到问题,问题是当我将 json 发送到服务器时,它就像 json 密钥一样使用它。我正在使用body-parser,也许问题出在那个?这是我的代码:

角度:

var request = $http({
    method: "POST",
    url: 'http://localhost:3000/register',
    data: {
        "username": "filip"
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

node.js

var express = require("express");
var bodyParser = require("body-parser");
var morgan = require("morgan");
var app = express();
var config = require("./config");
var mongodb = require("mongodb")

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(morgan("dev"));

app.post("/register", function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    console.log(req.body);
});

这就是我在服务器上收到的请求:

{ '{"username":"filip"}': '' }

我刚刚开始学习 node.js,我被这个简单的东西困住了, 有人帮忙吗?

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    您正在使用 application/x-www-form-urlencoded 作为内容类型,这是 JSON 之外的另一种 mime 类型。要发送 JSON,您可以使用

    $http.post('http://localhost:3000/register', { "username": "filip" })
    

    请注意,我跳过了在标题中指定内容类型。如果您不指定其他内容,application/json 是 POST 的默认内容类型。

    【讨论】:

    • ty 响应,是的,我尝试了,但是我无法将请求发送到服务器.. 错误:无法加载 localhost:3000/register:对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin' 标头出现在请求的资源上。因此,不允许访问 Origin 'localhost:8080'。
    • 我安装了插件 cors,现在当我使用 post 方法时出现 404 错误,但如果使用 put 方法它工作正常..为什么 post 方法不起作用?
    • @fvukovic 您可以尝试按照this 答案中的说明设置 CORS。您在问题中将'http://localhost:8080' 作为允许的来源,但您发送到'http://localhost:3000'。尝试将允许的来源更改为 *。
    猜你喜欢
    • 1970-01-01
    • 2014-07-31
    • 2018-11-27
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2022-01-07
    • 2017-03-05
    • 1970-01-01
    相关资源
    最近更新 更多