messageToCosmos 函数在我的虚拟项目中起作用,但在这里不起作用;我越来越
{ 错误:缺少必需的标头授权。确保有效 授权令牌已通过。活动ID: 1250064f-f72d-4b73-adb7-4f2bcd91e778, Microsoft.Azure.Documents.Common/2.7.0
请找到messageToCosmos函数,你可以尝试一下我已经给出了我的key和endpoint
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
require('dotenv').config();
var fs = require('fs');
var https = require('https');
var http = require('http');
const app = express();
const dbString = 'mongodb://localhost:27017/blue-isSecure';
const messageRoute = require('./routes/messages')
const multer = require('multer');
const path = require('path');
// const fileUpload = require('express-fileupload');
const cors = require('cors')
const cron = require('node-cron')
// cosmos
const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('./config')
const endpoint = config.endpoint;
const cosmosKey = config.key;
const client = new CosmosClient({ endpoint, cosmosKey });
const databaseId = config.database.id
const containerId = config.container.containerMessages
const fileStorage = multer.diskStorage({
destination:(req, file, cb ) =>{
cb(null,'files')
},
filename:(req, file, cb) => {
cb(null, file.originalname)
}
})
// app.use(cors)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.use(multer({storage:multer.memoryStorage()}).single('file'))
// app.use(fileUpload({
// useTempFiles:true
// }))
app.use('/files', express.static(path.join(__dirname,'files')))
app.use('/blue-isSecure',messageRoute)
async function messageToCosmos(itemBody) {
const { item } = await client.database(databaseId).container(containerId).items.upsert(itemBody);
console.log(`Created family item with id:\n${itemBody.id}\n`);
};
messageToCosmos({message:'hey buddy'}).catch(err =>console.log(err))
mongoose.connect(dbString,{useNewUrlParser:true, useUnifiedTopology:true})
.then(connect =>{
app.listen(process.env.PORT || 2020)
console.log('listening')
})
.catch(err => {
console.log(err)
})
我的配置文件
var config = {}
config.endpoint = "https://bluecosmosdb.documents.azure.com:443/";
config.key = "j2EFBfUe1GQpd5Sewv0LXUUluhrjdOuQ0w14JkJYSe4ISVkN9SBBPxq8wynW6bs7QCicbYsB6DaAfVd5Q1K6Nw==";
config.database = {
id: 'blueSecures'
}
config.container = {
containerMessages: 'messages'
}
module.exports = config;
它对我有用:
卸载 @azure/cosmos 并使用 2.1.7 版本重新安装 (npm install @azure/[email protected] --save)
参考链接(感谢@kilmfer91)
问题在于 OP 代码将“key”变量重命名为“cosmosKey”。要修复它:
const client = new CosmosClient({ endpoint, key: cosmosKey });
在我的node.js服务器代码上添加带有extend:true的body-parser后检索授权标头
app.use(bodyParser.urlencoded({扩展:true}))