我正在构建一个Outlook API addin和一个REST API lever node/express。我已经构建了 api 端,我可以成功调用并显示来自 POSTMAN 的请求,但是当我使用 javascript 调用时,请求是空的。API 中的显示显示未定义。
任务窗格.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));
});
'''
这是我的接口 索引.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;
});
'''
您的服务器需要带有 JSON 正文的请求,但您正在发送 url 编码的数据.
要发送 JSON,您必须将 ojbject 字符串化为 JSON,请参见下文
$.ajax({
url: apiurl,
method: 'POST',
type: 'json',
data: JSON.stringify(request),
contentType: 'application/json'
})