2 回答
![?](http://img1.sycdn.imooc.com/5458506b0001de5502200220-100-100.jpg)
TA贡献1898条经验 获得超8个赞
我认为您正在尝试在同一个 URL 上提供您的前端和 JSON 数据/。
您需要调整您的服务器代码如下:
let express = require('express');
let app = express();
app.use(express.static(`main`));
app.get('/api', function(req, res){
res.json(data); //also tried to do it through .send, but there data only on window in browser
});
app.listen(3000);
现在您的数据将以 JSON 格式从/api. 然后你可以在前端发出如下请求:
let dataName = [];
let request = async () => {
const response = await fetch('http://localhost:3000/api');
const data = await response.json();
dataName = data.name;
}
let name = document.getElementById('name');
name.textContent = dataName;
还有一个问题是url没有正确定义为参数。我调整了函数以在正确的位置简单地使用 URL 字符串。
![?](http://img1.sycdn.imooc.com/533e4d5b0001d57502200203-100-100.jpg)
TA贡献1850条经验 获得超11个赞
您可以创建一个可以使用REST API进行通信的服务器
(假设数据是一个字符串)
客户:
let data = getSomeDataYouWantToSend()
fetch('/send', {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: data
})
假设您在目录中有静态文件,在目录中/main有 html 文件/views
服务器:
let express = require('express')
let app = express()
app.use(express.static(`${__dirname}/main`))
app.set('views', `${__dirname}/views`)
app.get('/', (req, res) => {
res.render('index.html')
})
app.post('/send', (req, res) => {
console.log(req.body) // <- here is your data sent from client frontend
})
app.listen(3000)
添加回答
举报