方法1:
import {Injectable} from '@nestjs/common';
import {SQS} from 'aws-sdk';
@Injectable()
export class SqsService {
private client: SQS;
private awsAccessKey = process.env.AWS_ACCESS_KEY_ID;
private awsSecretKey = process.env.AWS_SECRET_ACCESS_KEY;
private awsRegion = process.env.AWS_REGION;
constructor() {
this.client = new SQS({
credentials: {
accessKeyId: this.awsAccessKey,
secretAccessKey: this.awsSecretKey,
},
region: this.awsRegion,
sslEnabled: true,
});
/**
* The code below is used for testing if the SQS service works.
*/
this.client.listQueues({}, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
}
方法2:
import {Injectable} from '@nestjs/common';
import {AWSError, SQS} from 'aws-sdk';
const AWS = require('aws-sdk');
@Injectable()
export class SqsService {
private client: SQS;
private awsAccessKey = process.env.AWS_ACCESS_KEY_ID;
private awsSecretKey = process.env.AWS_SECRET_ACCESS_KEY;
private awsRegion = process.env.AWS_REGION;
constructor() {
this.client = new AWS.SQS({
credentials: {
accessKeyId: this.awsAccessKey,
secretAccessKey: this.awsSecretKey,
},
region: this.awsRegion,
sslEnabled: true,
});
/**
* The code below is used for testing if the SQS service works.
*/
this.client.listQueues({}, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
}
}
以上两种方法都是正确的。
以下报错产生于 this.client.sendMessage() ,但是报错信息中确有 InvalidClientTokenId: The security token included in the request is invalid. 的字样,sendMessage 代码与官方文档一致,令人困惑。
this.client.sendMessage(sendMessageRequest, (err, data) => {
if (err) console.log(err); // an error occurred
else console.log(data); // successful response}
});
原因是队列的 URL 写错了!