SDK-NodeJS icon indicating copy to clipboard operation
SDK-NodeJS copied to clipboard

Unauthorized error on message POST request using addReply and reply functions

Open tdakinosho opened this issue 4 years ago • 0 comments

Hi everyone,

I would appreciate any suggestions to help resolve the issue i am currently experiencing (Please see generated error in attached file). Everything seemed to be working fine till a few weeks ago. I use the sdk to receive and send messages to a SAP chatbot as shown in the code below. I keep getting an unauthorised error even after trying with both the designtime and runtime oauth credentials.

let token = process.env.SAPCAI_TOKEN;
let client = new sapcai.connect(token);


let app = express();
const jsonParser = bodyParser.json();
app.use(cors());
app.use(jsonParser);
app.use(express.static('customwidget'));
app.use(serveStatic(path.join(__dirname, '/../sapcaiWidget')));
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    const reqId = uuid();
    res.locals.log = log.child({ reqId });
    next();
});

With the token generated as below:

const getToken = async () => {

    const options = {
        url: process.env.SAPCAI_AUTH_URL,
        type: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        params: {
            grant_type: 'client_credentials'
        },
        auth: {
            username: process.env.SAPCAI_CLIENT_ID,
            password: process.env.SAPCAI_CLIENT_SECRET
        }
    };
    try {
        const result = await axios.request(options)
            .then(function (response) {
                return response.data;
            }).catch(function (error) {
                return error.response ? error.response : error;

            });
        return result;
    }
    catch (err) {
        console.error(err)
    }

};



const getAccessToken = () => {
    let setToken = getToken().then((val) => {
        axios.defaults.headers.common['Authorization'] = `Bearer ${val.access_token}`; //
        axios.defaults.headers.common['X-Token'] = `Token ${token}`;
    });
    return setToken;
}

I am able to send messages to the bot successfully using the code snippet below:

let url = "https://api.cai.tools.sap/build/v1/dialog";
    console.log(url)
    let data  = {
        "message": {
            "content": "Hello SAP Conversational AI",
            "type": "text"
        },
        "conversation_id": conversationId
    };

    axios.post(url, data).then(function (response) {
        console.log(`Status: ${response.data}`);
    }).catch(function (error){
        let errorCode = error.response.status;
        if(errorCode === 401) {
            getAccessToken();
            initChat(conversationId, socketid);
        }
        return errorCode;
    });

However when i try to update an existing conversation the error in the attached file gets generated. i have tried to trace the error to the addReply and Reply functions in /src/apis/resources/message.js but still unable to figure out what causes it.

Any help or suggestions will be highly appreciated. Thanks

error.txt

tdakinosho avatar Jan 19 '22 11:01 tdakinosho