Reputation: 374
I am building an outlook API addin and a REST API leverage node/express. I have build out the api side and I can successfully call and display the request from POSTMAN but when I call with the javascript the request is empty. The display in the API shows undefined.
taskpane.js
'''
function checkBodyforLinks(){
Office.context.mailbox.item.body.getAsync(
"html",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
var parser = new DOMParser();
var bodyHtml = parser.parseFromString(result.value, "text/html");
//need to add check to ignore mailto: links
var linkDomains = [], links = bodyHtml.links;
document.getElementById("linkCheck").innerHTML = "No links found within email body";
for (var i = 0; i < links.length; i++){
linkDomains.push(links[i].href);
}
if(linkDomains.length > 0) {
var apiurl = 'http://localhost:5000/linkcheck';
var request = {
"link": linkDomains[0]
};
console.log(request);
$.ajax({
url: apiurl,
method: 'POST',
type: 'json',
data: request
}).done(
function(data){
console.log("successfully called API");
console.log(JSON.stringify(data));
}).fail(function(error){
console.log("api call failed");
console.log(JSON.stringify(error));
});
'''
Here is my API index.js '''
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(express.json());
app.use(bodyParser.json());
app.listen(5000, () => {
console.log("Server running on port 5000");
});
app.post('/linkcheck', (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
console.log(req.body.link);
res.status(200).json({
message: "Successfully called API"
});
return res;
});
'''
Upvotes: 2
Views: 734
Reputation: 97717
Your server is expecting a request with a JSON body but you're sending url encoded data.
To send JSON you have to stringify the ojbject into JSON, see below
$.ajax({
url: apiurl,
method: 'POST',
type: 'json',
data: JSON.stringify(request),
contentType: 'application/json'
})
Upvotes: 1