2 回答

TA貢獻1898條經(jīng)驗 獲得超8個贊
我認為您正在嘗試在同一個 URL 上提供您的前端和 JSON 數(shù)據(jù)/。
您需要調(diào)整您的服務(wù)器代碼如下:
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);
現(xiàn)在您的數(shù)據(jù)將以 JSON 格式從/api. 然后你可以在前端發(fā)出如下請求:
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沒有正確定義為參數(shù)。我調(diào)整了函數(shù)以在正確的位置簡單地使用 URL 字符串。

TA貢獻1850條經(jīng)驗 獲得超11個贊
您可以創(chuàng)建一個可以使用REST API進行通信的服務(wù)器
(假設(shè)數(shù)據(jù)是一個字符串)
客戶:
let data = getSomeDataYouWantToSend()
fetch('/send', {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: data
})
假設(shè)您在目錄中有靜態(tài)文件,在目錄中/main有 html 文件/views
服務(wù)器:
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)
添加回答
舉報