2 回答

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 字符串。

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)
添加回答
舉報