【问题标题】:Empty body after a jQuery POST requestjQuery POST 请求后的空正文
【发布时间】:2019-11-18 21:02:59
【问题描述】:

关于我正在开发的 Forge Autodesk 查看器的问题,我需要您的帮助,基于 this tutorial。 查看器包含创建存储桶的功能,但此功能不适用于我的查看器版本,因为创建存储桶的 POST 请求不包含正文。

存储桶创建功能在教程查看器上功能齐全,我的代码基于此功能。我对此很陌生,所以如果我错过了一些重要的部分,我会尽快提供!

bucket创建代码,客户端:

  function createNewBucket() {
    var bucketKey = $('#newBucketKey').val();
    var policyKey = $('#newBucketPolicyKey').val();
    console.log(bucketKey)
    jQuery.post({
      url: '/api/forge/oss/buckets',
      contentType: 'application/json',
      data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
      success: function (res) {
        $('#appBuckets').jstree(true).refresh();
        $('#createBucketModal').modal('toggle');
      },
      error: function (err) {
        if (err.status == 409)
          alert('Bucket already exists - 409: Duplicated')
        console.log(err);
      }
    });
  }

存储桶创建代码,服务器端:

// POST /api/forge/oss/buckets - creates a new bucket.
// Request body must be a valid JSON in the form of { "bucketKey": "<new_bucket_name>" }.
router.post('/buckets', async (req, res, next) => {
    let payload = new PostBucketsPayload();
    console.log(req)
    payload.bucketKey = config.credentials.client_id.toLowerCase() + '-' + req.body.bucketKey;
    payload.policyKey = 'transient'; // expires in 24h
    try {
        // Create a bucket using [BucketsApi](https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/BucketsApi.md#createBucket).
        await new BucketsApi().createBucket(payload, {}, req.oauth_client, req.oauth_token);
        res.status(200).end();
    } catch(err) {
        next(err);
    }
});

预期的请求(在 VSCode 上显示,来自工作代码):

IncomingMessage {_readableState: ReadableState, readable: false, _events: Object, _eventsCount: 1, _maxListeners: undefined, …}
oss.js:60
_body:true
_consuming:true
_dumped:false
_events:Object {end: }
_eventsCount:1
_maxListeners:undefined
_parsedUrl:Url {protocol: null, slashes: null, auth: null, …}
_readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, …}
[[StableObjectId]]:1
aborted:false
baseUrl:"/api/forge/oss"
body:Object {bucketKey: "buckettest"}
client:Socket {connecting: false, _hadError: false, _handle: null, …}
complete:true
connection:Socket {connecting: false, _hadError: false, _handle: null, …}
destroyed:false
fresh:false
headers:Object {host: "localhost:3001", user-agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0)…", accept: "*/*", …}
host:"localhost"
hostname:"localhost"
httpVersion:"1.1"
httpVersionMajor:1
httpVersionMinor:1
ip:undefined
ips:Array(0)
length:undefined
method:"POST"
next:function next(err) { … }
oauth_client:OAuth2TwoLegged {authentication: Object, authName: "oauth2_application", clientId: "rt2DhnuChgIIEX3GhnGyeISPS9Vzoh3p", …}
oauth_token:Object {access_token: "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2…", token_type: "Bearer", expires_in: 3599, …}
originalUrl:"/api/forge/oss/buckets"
params:Object {}
path:"/buckets"
protocol:"http"
query:Object {}
rawHeaders:Array(22) ["Host", "localhost:3001", "User-Agent", …]
rawTrailers:Array(0) []
readable:false
readableBuffer:BufferList
readableFlowing:true
readableHighWaterMark:16384
readableLength:0
res:ServerResponse {_events: Object, _eventsCount: 1, _maxListeners: undefined, …}
route:Route {path: "/buckets", stack: Array(1), methods: Object}
secure:false
socket:Socket {connecting: false, _hadError: false, _handle: null, …}
stale:true
statusCode:null
statusMessage:null
subdomains:Array(0)
[[StableObjectId]]:2
length:0
__proto__:Array(0) [, …]
trailers:Object {}
upgrade:false
url:"/buckets"
xhr:true
__proto__:IncomingMessage {app: }

实际请求(在 VSCode 上显示,来自非工作代码):

IncomingMessage {_readableState: ReadableState, readable: true, _events: Object, _eventsCount: 1, _maxListeners: undefined, …}
oss.js:61
_consuming:false
_dumped:false
_events:Object {end: }
_eventsCount:1
_maxListeners:undefined
_parsedUrl:Url {protocol: null, slashes: null, auth: null, …}
_readableState:ReadableState {objectMode: false, highWaterMark: 16384, buffer: BufferList, …}
[[StableObjectId]]:1
aborted:false
baseUrl:"/api/forge/oss"
client:Socket {connecting: false, _hadError: false, _handle: TCP, …}
complete:true
connection:Socket {connecting: false, _hadError: false, _handle: TCP, …}
destroyed:false
fresh:false
headers:Object {host: "localhost:3000", user-agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0)…", accept: "*/*", …}
host:"localhost"
hostname:"localhost"
httpVersion:"1.1"
httpVersionMajor:1
httpVersionMinor:1
ip:"::1"
ips:Array(0)
method:"POST"
next:function next(err) { … }
oauth_client:OAuth2TwoLegged {authentication: Object, authName: "oauth2_application", clientId: "rt2DhnuChgIIEX3GhnGyeISPS9Vzoh3p", …}
oauth_token:Object {access_token: "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2…", token_type: "Bearer", expires_in: 3599, …}
originalUrl:"/api/forge/oss/buckets"
params:Object {}
path:"/buckets"
protocol:"http"
query:Object {}
rawHeaders:Array(22) ["Host", "localhost:3000", "User-Agent", …]
rawTrailers:Array(0) []
readable:true
readableBuffer:BufferList
readableFlowing:null
readableHighWaterMark:16384
readableLength:27
res:ServerResponse {_events: Object, _eventsCount: 1, _maxListeners: undefined, …}
route:Route {path: "/buckets", stack: Array(1), methods: Object}
secure:false
socket:Socket {connecting: false, _hadError: false, _handle: TCP, …}
stale:true
statusCode:null
statusMessage:null
subdomains:Array(0)
trailers:Object {}
upgrade:false
url:"/buckets"
xhr:true
__proto__:IncomingMessage {app: }

错误信息(在 VSCode 上显示):

(node:15636) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'bucketKey' of undefined
[...]
(node:15636) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
warning.js:18
(node:15636) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

  • 您的 createBucket 函数似乎有问题,请检查一次
  • @ArvindRajput 函数createBucket 不是我的,它来自Bucket API,它在教程的工作版本中正常工作。加上这个方法是在请求发送后调用的,如果我得到它正确?
  • 在非工作版本中,请求正文似乎还没有被express读取。您能否确认您已为 JSON 配置了适当的快速中间件? app.use(express.json({ limit: '50mb' }));
  • Learnforge 教程中如何配置中间件:github.com/Autodesk-Forge/learn.forge.viewmodels/blob/nodejs/….
  • @PetrBroz 就是这样!非常感谢,现在我在 start.js 中添加了这一行代码有效!这条线的确切含义是什么?正如我所说,我对此很陌生^^'

标签: javascript jquery json autodesk-forge autodesk-model-derivative


【解决方案1】:

由于您的请求的 readable 属性是 true,因此 express 应用程序可能尚未解析其主体。确保按照教程中的this line 所示设置 JSON 解析中间件。使用此中间件,您的 express 应用将自动读取带有 Content-Type: application/json 的任何传入请求的正文。

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2019-06-26
    • 1970-01-01
    • 2021-03-20
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多