我首先从我的后端外部api获取xml数据,然后试图将其发送到前端。
后端(服务器):
app.get("/api", (req, res) => {
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://link',
'headers': {
}
};
request(options, function (error, response) {
console.log("TEST1")
console.log(response.body)
if (error){
console.log("TEST2")
res.status(404).write("NO LUCK");
}
console.log("TEST3")
res.status(200).write(response.body);
});
});
xml正确地显示在我的终端中。TEST1和TEST2也是。
前端(客户端):
import XMLParser from 'react-xml-parser';
useEffect(() => {
fetch("/api")
.then(res => res.text())
.then(data => {
var xml = new XMLParser().parseFromString(data);
console.log(xml)
})
.catch(err => console.log(err));
}, []);
控制台没有显示任何内容。我从这个堆栈溢出的帖子中得到了前端代码。
fetch("/api")
.then((res) => res.body)
.then((data) => console.log(data));
如果我像这样记录响应体,我会得到一个ReadableStream对象。这是唯一的功能,我已经实现到目前为止,所以没有应该干扰它。当我尝试不同的方法时,我总是需要重新启动React,否则当我刷新时它会没完没了地加载。
当我打开http://localhost:3001/api时,我可以看到我试图传输的xml数据。
仍然不确定为什么它之前不工作,但它与这个工作。
前端(客户端):
import axios from "axios";
axios.get('/api')
.then(xml => {
console.log(xml.data);
})
后端(服务器):
app.get('/api', (req, res) => {
var axios = require('axios');
var config = {
method: 'get',
url: 'http://link',
headers: {'Content-Type': 'application/xml'}
};
axios(config)
.then(function (response) {
res.json(response.data);
})
.catch(function (error) {
console.log(error);
})
})