0

app.js 中的这段代码:

var express = require('express'),
    app     = express(),
    port    = parseInt(process.env.PORT, 10) || 3000;

app.configure(function(){
    app.use(express.bodyParser());
    app.use(app.router);
 });

app.listen(port);

app.post("/", function(req, res) {
    console.log("Body: " + req.body);
    res.send({ status: 'SUCCESS' });
});

跑步

 PS C:\> curl -X POST -H "Content-Type:application/json" -d '{"type":"server","name":"SERVER1"}' http://localhost:3000/

结果是:

SyntaxError: Unexpected token t
at Object.parse (native)
at IncomingMessage.<anonymous (C:\temp\neo4jstest2\node_modules\express\node_modules\connect\lib\middleware\json.js
:76:27)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at _stream_readable.js:910:16
at process._tickCallback (node.js:415:13)

我已经在 Ubuntu 13.04 上测试了相同的代码,它运行良好。

在 Windows 上是否有任何差异或调整以使其正常工作?

4

3 回答 3

1

Powershell 救援:

PS:\> $body = ConvertTo-Json @{"type" = "server"; "name" = "SERVER1"}
PS:\> Invoke-WebRequest -Body $body -Uri http://localhost:3000/ -ContentType application/json -Method POST
于 2013-08-12T07:46:02.103 回答
0

对于我使用 curl 的 Windows 64 位机器,这对我有用:

curl -H "Content-Type: application/json" -X POST
 -d "{\"firstName\":\"First\", \"lastName\":\"Last\", \"email\":\"user@example.c
om\", \"username\":\"username\", \"password\":\"password\"}" localhost:3000/user
s
于 2015-11-06T20:40:35.023 回答
-1

Windows 命令行不喜欢使用单引号。我还没有尝试过,但我相信这会奏效:

curl -X POST -H "Content-Type:application/json" -d "{\"type\":\"server\",\"name\":\"SERVER1\"}"

单引号已替换为双引号,内部双引号已转义。

更新

我能够在我的本地 Windows 7(64 位)机器上运行它:

C:\>f:\util\curl.exe -X POST -H "Content-Type:application/json" -d "{\"type\":\"server\",\"name\":\"SERVER1\"}" http://localhost:3000/
{
  "status": "SUCCESS"
}

curl 版本(刚刚从http://curl.haxx.se/下载)

C:\>f:\util\curl.exe --version
curl 7.31.0 (x86_64-pc-win32) libcurl/7.31.0
Protocols: dict file ftp gopher http imap ldap pop3 rtsp smtp telnet tftp
Features: AsynchDNS GSS-Negotiate Largefile NTLM SSPI

节点版本:

C:\>node --version
v0.8.18

使用单引号(同时使用转义的双引号和未转义的双引号)运行会导致此错误:

Error: invalid json
    at Object.exports.error (F:\tmp\stackoverflow\node_modules\express\node_modules\connect\lib\utils.js:62:13)
    at IncomingMessage.module.exports (F:\tmp\stackoverflow\node_modules\express\node_modules\connect\lib\middleware\json.js:74:71)
    at IncomingMessage.EventEmitter.emit (events.js:93:17)
    at IncomingMessage._emitEnd (http.js:366:10)
    at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
    at Socket.socket.ondata (http.js:1786:22)
    at TCP.onread (net.js:404:27)
于 2013-08-11T20:50:41.780 回答