Node.js React、Node Js和Express无法获取/出现问题
打开我的应用程序时遇到问题。我已经使用createreact应用程序(后端的nodejs和express)构建了这个应用程序,它是“colorsofemre.com”。但是,当我尝试在应用程序中进行更改时,我得到的只是浏览器上的“无法获取/错误” 这是我的server.jsNode.js React、Node Js和Express无法获取/出现问题,node.js,reactjs,express,server,get,Node.js,Reactjs,Express,Server,Get,打开我的应用程序时遇到问题。我已经使用createreact应用程序(后端的nodejs和express)构建了这个应用程序,它是“colorsofemre.com”。但是,当我尝试在应用程序中进行更改时,我得到的只是浏览器上的“无法获取/错误” 这是我的server.js const express = require('express') const app = express() port = process.env.PORT || 3000 ; var bodyParser = requ
const express = require('express')
const app = express()
port = process.env.PORT || 3000 ;
var bodyParser = require('body-parser')
var path = require("path")
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.use('public', express.static(path.join(__dirname, 'src')));
app.use('public', express.static(path.join(__dirname, 'public')));
app.get('/color', async (req, res) => {
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
if (err) return console.log(err)
// Storing a reference to the database so you can use it later
db = client.db('ColorPicker')
db.collection('Colors').find({}).toArray((err,result)=>{
if(err) throw err;
console.log(result);
res.status(200).json(result)
console.log(result);
})
});
});
app.listen(port,()=>{console.log("Listening on port"+port)});
这是我的客户端获取函数get/color
async updateArray(){
this.colors=[];
const result = await fetch(`http://localhost:3000/color`,{mode: 'cors'});
const data = await result.json();
this.arrayModified(data);
this.setState({render:true});
}
当我启用客户端时,我得到了这个错误
Unhandled Rejection (SyntaxError): The string did not match the expected pattern.
21 |
22 | this.colors=[];
23 | const result = await fetch(`http://localhost:3000/color`,{mode: 'cors'});
> 24 | const data = await result.json();
| ^ 25 | this.arrayModified(data);
26 | this.setState({render:true});
27 | }
如果我对客户端获取代码进行注释,我只会在浏览器上获取Cannot/get。数据库工作正常,当我转到localhost:3000/color时,json数据被完美加载
我的文件结构是
-public
-index.html
-src
-index.js
-app.js
-and other js components
-server.js
两天来我一直在想到底出了什么问题。谢谢你 尝试向您的
server.js
添加这样一个“一网打尽”的路由,首先将GET请求重定向到index.html
:
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
来源:执行此操作时,浏览器仅打开index.html文件(为空),而不连接index.js文件以连接组件。我试着把它放进去,但它仍然不起作用,而且还带来了额外的问题。