0

我正在使用胡萝卜2s api:

const xml = 
`<?xml version="1.0" encoding="UTF-8"?>
<searchresult>
<query>bob</query>
    <document id="https://api.cognitive.microsoft.com/api/v7/#WebPages.0">
        <title>Bob O's Family Fun Center | El Paso, TX</title>
        <url>http://www.bing.com/cr?IG=29AD4AB87B7B438D8F2AA5967E17967DCID=24C5C22679EF67D1293BCE6078F66638rd=1h=AaGhCeGCFZPjz86DB6AZMIlM8b3VlbHiXWyUPsmFL_k=1r=http%3a%2f%2fbobosfun.com%2fp=DevEx.LB.1,5071.1</url>
        <snippet>Bob-O’s is El Paso’s Premier Family Fun Center. Located on the Westside off Sunland Park Drive, Bob-O’s offers a variety of entertainment for the entire family.</snippet>
    </document>
</searchresult>`

    fetch(`carrot2server/dcs/rest`, {
        method: 'POST',
        body: {
            'dcs.c2stream': xml,
            'results': 100,
            'dcs.algorithm': 'lingo',
            'dcs.output.format': 'JSON'
        }
    })
    .then(function(response) {
    response.text().then(function(text) {
        console.log(text);
    })
}).catch(function(err) {
  console.log(err)
});

如果我在邮递员中运行相同的请求,我会得到预期的结果。

我收到的错误是:

HTTP 状态 400 – 错误请求

必须提供 dcs.source 或 dcs.c2stream 中的非空文档列表

由于某些被认为是客户端错误(例如,格式错误的请求语法、无效的请求消息帧或欺骗性请求路由),服务器不能或不会处理请求。

4

1 回答 1

0

通过设置正确的 encodeURIComponent 并添加内容类型来解决此问题:application/x-www-form-urlencoded

const params = {
        'dcs.c2stream': xml,
        'results': 100,
        'dcs.algorithm': 'lingo',
        'dcs.output.format': 'JSON'
}

const searchParams = Object.keys(params).map((key) => {
    return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');

fetch('carrot2server/dcs/rest', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: searchParams
})
.then(function(response) {
    response.text().then(function(text) {
        console.log(text);
    })
}).catch(function(err) {
  console.log(err)
});
于 2018-08-14T16:52:35.590 回答