2017-07-25 91 views
0

我正在尝试使用Javascript的fetch方法进行POST请求,如here所述。如何使用Javascript的获取获取POST请求数据?

我得到一个ReadableStream而不是通常的json响应,比如我会用jQuery,Angular获得什么。

我的代码是在这里:https://jsbin.com/vuwilaviva/edit?css,js,output

var request = new Request('https://httpbin.org/post', { 
    method: 'POST', 
    mode: 'cors', 
    data: 'The sky is green', 
    redirect: 'follow', 
    headers: new Headers({ 
     'Content-Type': 'text/plain' 
    }) 
}); 


// Now use it! 
fetch(request).then(function(resp) { 
    console.log('Logging response...') 
    console.log(resp); 
}); 

测试API端点正常工作与邮差,卷曲等,所以我相信我现在用fetch错了,这不是与API的问题(它刚刚返回的任何字符串传递给它的data):

enter image description here

编辑:目前的答案实际上不获取数据通过发布请求返回 - 它远不在登录json被发现:

enter image description here

+0

您在'body'属性传递数据。 –

+0

该链接告诉你如何从响应中获取JSON,在标题部分**处理JSON ** ... –

+0

@MikeMcCaughan不起作用。 – VSO

回答

2

response.json应该用于此

fetch(request) 
.then(response => response.json()) 
.then(json => console.log(json)); 
+2

有趣的事实:你现在可以在chrome中使用'.then(console.log)',或许其他人(他们修复'this') – dandavis

+0

@pethel:这里有两件事 - 1.这并不能得到我需要的东西 - 我在json中看不到响应字符串。你能解释一下你的答案吗,为什么那两个陈述?不是调用已经是异步的,为什么响应是一个流? – VSO

+0

@VSO你现在的问题是contenttype response.json() - > response.text(),你可以将内容记录为文本。尝试更改为application/json,但您还需要调整您的服务器代码,因为。 – pethel