จะให้บริการแอปโต้ตอบด้วย node.js ได้อย่างไร

ฉันสงสัยมาตลอดว่า React routing ทำงานอย่างไรในแอปหน้าเดียว ตัวอย่างเช่น เมื่อฉันต้องการไปที่ https://example.com/a จะรู้ได้อย่างไรว่า "a" เป็นเส้นทาง React ใน example.com และไม่พยายามไปที่ https://example.com/a/ ที่ไม่มีอยู่

ตอนนี้ฉันมีปัญหากับเรื่องนั้น ฉันสร้างแอป React หน้าเดียวพร้อมการกำหนดเส้นทาง และโฮสต์เวอร์ชันที่สร้างขึ้นด้วย node.js ด้วยรหัสต่อไปนี้:

const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build_webpack')));
app.listen(3000, function() {
    console.log('Listening on ' + port);
})

เมื่อฉันไปที่ localhost:3000 และไปที่ localhost:3000/route ภายในแอป มันก็ทำงานได้ดี อย่างไรก็ตาม หากฉันพิมพ์ localhost:3000/route ในเบราว์เซอร์แล้วกด Enter มีข้อผิดพลาดแจ้งเกี่ยวกับ:

Refused to load the font '<URL>' because it violates the following Content Security
Policy directive: "default-src 'self'". Note that 'font-src' was not explicitly set,
so 'default-src' is used as a fallback."

ซึ่งเป็นข้อผิดพลาดเดียวกับที่ฉันได้รับเมื่อพยายามเยี่ยมชมเส้นทางที่ไม่มีอยู่: localhost:3000/routeThatDoesntExist

ฉันคิดว่าปัญหาอาจเกิดจากการที่ฉันเซิร์ฟเวอร์แอปด้วย node.js ได้อย่างไร


person longcc    schedule 20.05.2018    source แหล่งที่มา


คำตอบ (1)


คุณต้องบอกให้เซิร์ฟเวอร์ส่ง index.html ในเส้นทางใดๆ ก็ตามที่เซิร์ฟเวอร์พบ

สำหรับเช่น:

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

สร้างเอกสารแอป React

person Agney    schedule 20.05.2018
comment
ขอบคุณ. แต่ด้วยเหตุผลบางประการ มันไม่ได้ผล มิดเดิลแวร์ express.static จับเส้นทางย่อยได้ ฉันต้องใช้ app.use(function(req,res){res.sendFile(path.join(__dirname, 'build', 'index.html'));}); และตอนนี้มันใช้งานได้ - person longcc; 20.05.2018