Мне нужна ваша помощь с проблемой, связанной с Forge Autodesk Viewer, которую я разрабатываю на основе этот учебник. Средство просмотра включает функцию создания сегментов, и эта функция не работает в моей версии средства просмотра, поскольку запрос POST на создание сегмента не содержит тела.
Функция создания корзины полностью функциональна в средстве просмотра учебных пособий, и я основывал свой код на ней. Я новичок в этом, поэтому, если я пропущу некоторые важные детали, я предоставлю их как можно скорее!
Код создания корзины на стороне клиента:
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
console.info(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.info(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.info(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.
@ArvindRajput функция createBucket не моя, она взята из Ведро API и работает правильно в рабочей версии из туториала. Плюс этот метод вызывается после отправки запроса, если я правильно понимаю?
Похоже, что в нерабочей версии тело запроса еще не прочитано экспрессом. Можете ли вы подтвердить, что вы настроили соответствующее ПО промежуточного слоя Express для JSON? app.use(express.json({ limit: '50mb' }));
Вот как промежуточное ПО настраивается в учебном пособии Learnforge: github.com/Autodesk-Forge/learn.forge.viewmodels/blob/nodejs/….
@PetrBroz вот и все! Большое спасибо, теперь я добавил эту строку в свой start.js, код работает! Что именно означает эта строка? Как я уже сказал, я новичок в этом ^^'
Нет проблем :) Позвольте мне обобщить это в ответе ниже, чтобы другие тоже могли его найти.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Поскольку свойство readable вашего запроса равно true, возможно, экспресс-приложение еще не проанализировало его тело. Обязательно настройте промежуточное ПО для синтаксического анализа JSON, как показано на эта линия в руководстве. С этим промежуточным ПО ваше экспресс-приложение будет автоматически считывать тело любого входящего запроса с помощью Content-Type: application/json.
похоже, что-то идет не так в вашей функции createBucket, пожалуйста, проверьте ее один раз