简体   繁体   English

Javascript AJAX 传递未定义的 request.body

[英]Javascript AJAX passing undefined request.body

I am building an outlook API addin and a REST API leverage node/express.我正在构建一个 outlook API 插件和一个 REST ZDB974238714CA8DE634A7CE1DZF 杠杆节点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.我已经构建了 api 端,我可以成功调用并显示来自 POSTMAN 的请求,但是当我使用 javascript 调用时,请求为空。 The display in the API shows undefined. API 中的显示显示未定义。

taskpane.js任务窗格.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 '''这是我的 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;
});

''' '''

Your server is expecting a request with a JSON body but you're sending url encoded data.您的服务器期待一个带有 JSON 主体的请求,但您发送的是 url 编码数据。
To send JSON you have to stringify the ojbject into JSON, see below要发送 JSON,您必须将 ojbject 字符串化为 JSON,见下文

      $.ajax({
        url: apiurl,
        method: 'POST',
        type: 'json',
        data: JSON.stringify(request),
        contentType: 'application/json'
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM