Node.js 中的文档存储功能
本文介绍了一个使用 Node.js 和 Express.js 中的 文档存储功能 的应用程序示例。
此示例假定文档存储功能已正确启用。要了解如何启用文档存储,请参阅我们的 专用指南。
# 依赖项
此示例使用以下依赖项
axios
body-parser
cors
express
它还使用 Node.js 的核心依赖项:path
和 fs
。
# 示例
以下示例允许您上传 编辑器捆绑包,将文档导入存储,获取文档列表,获取文档以及删除文档。
此文件展示了一个简单的 Express.js 应用程序的示例。
请记住提供正确的 API 密钥并生成适当的 请求签名。
// index.js
const path = require( 'path' );
const fs = require( 'fs' );
const express = require( 'express' );
const axios = require( 'axios' );
const cors = require( 'cors' );
const bodyParser = require( 'body-parser' );
const generateSignature = require( './utils/generateSignature' ); // See: https://ckeditor.npmjs.net.cn/docs/cs/latest/examples/security/request-signature-nodejs.html.
const editorBundle = fs.readFileSync( path.resolve( '../client/build/ckeditor.js' ) ); // It should be your bundled editor.
const app = express();
const port = 8000; // The default application port.
const apiSecret = 'SECRET'; // Do not forget to hide this value in a safe place e.g. a .env file!
const organizationId = 'organizationId'; // Type your organization ID here.
const environmentId = 'environmentId'; // Type your environment ID here.
// If you use On-Premises application you can adjust baseApiUrl accordingly with your application URL.
const baseApiUrl = `https://${ organizationId }.cke-cs.com/api/v5/${ environmentId }`;
app.use( bodyParser.urlencoded( { extended: true } ) );
app.use( bodyParser.json() );
app.use( cors() );
// This function will be responsible for sending requests to CKEditor Cloud Services API.
async function sendRequest( method, url, body ) {
const CSTimestamp = Date.now();
const payload = {
method,
url,
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'X-CS-Signature': generateSignature( apiSecret, method, url, CSTimestamp, body ),
'X-CS-Timestamp': CSTimestamp
}
};
if ( method.toUpperCase() !== 'GET' ) {
payload.data = body;
}
try {
const { status, data } = await axios( payload );
return { status, data };
} catch ( { response } ) {
const { status, data } = response;
return { status, data };
}
}
// Upload the editor bundle. Note that you will need to upload your editor again if you change the bundle.
app.post( '/upload-editor', async ( req, res ) => {
const { bundleVersion } = req.body;
const { status, data } = await sendRequest( 'POST', `${ baseApiUrl }/editors`, {
bundle: editorBundle.toString(),
config: {
cloudServices: {
bundleVersion // This value should be unique per environment.
}
}
} );
return res.json( { status, data } );
} );
// Synchronously imports the document to the storage
app.post( '/storage', async ( req, res ) => {
const { documentId, documentContent } = req.body;
const { status, data } = await sendRequest(
'POST',
`${ baseApiUrl }/storage`,
{
document_id: documentId,
data: documentContent
}
);
return res.json( { status, data } );
} );
// Deletes a single document from the storage.
app.delete( '/storage/:documentId', async ( req, res ) => {
const { documentId } = req.params;
const { status } = await sendRequest( 'DELETE', `${ baseApiUrl }/storage/${ documentId }` );
return res.json( { status } );
} );
// Gets a single document.
app.get( '/storage/:documentId', async ( req, res ) => {
const { documentId } = req.params;
const { status, data } = await sendRequest( 'GET', `${ baseApiUrl }/storage/${ documentId }` );
return res.json( { status, data } );
} );
// Gets a list of documents.
app.get( '/storage', async ( req, res ) => {
const { status, data } = await sendRequest( 'GET', `${ baseApiUrl }/storage` );
return res.json( { status, data } );
} );
app.listen( port, () => console.log( `The application is listening on port ${ port }!` ) );
# 使用
运行
node index.js
通过向此应用程序发送 HTTP 请求,您现在可以执行操作并与 CKEditor 云服务进行通信。查看以下示例
- 上传编辑器捆绑包。
try {
const response = await fetch( 'http://localhost:8000/upload-editor', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify( { bundleVersion: '1.0.0' } )
} );
const data = await response.json();
console.log( 'Result of uploading editor:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}
- 同步将文档导入存储
try {
const response = await fetch( 'http://localhost:8000/storage', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify( {
documentId: "document-1",
documentContent: "<p>Lorem Ipsum is <b>simply dummy</b> text of the printing and typesetting industry.</p>",
} )
} );
const data = await response.json();
console.log( 'Result of inserting document:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}
- 获取文档列表 - 在
data
属性下应返回包含新创建的document-1
的数组。
try {
const response = await fetch( `http://localhost:8000/storage`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
} );
const data = await response.json();
console.log( 'Result of getting documents:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}
- 获取 ID 为
document-1
的文档。返回的内容应与步骤 2 中导入的内容相同。
try {
const response = await fetch( `http://localhost:8000/storage/document-1`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
} );
const data = await response.json();
console.log( 'Result of getting document:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}
- 删除 ID 为
document-1
的文档。
try {
const response = await fetch( `http://localhost:8000/storage/document-1`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
} );
const data = await response.json();
console.log( 'Result of deleting document:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}
- 尝试再次获取 ID 为
document-1
的文档。将抛出错误,说明该文档不存在。
try {
const response = await fetch( `http://localhost:8000/storage/document-1`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
} );
const data = await response.json();
console.log( 'Result of getting document:', data );
} catch ( error ) {
console.log( 'Error occurred:', error );
}