各位大佬求教,我最近搭了一个**react+nodejs+express**框架,是一个前后端分离的项目,express作为前端的服务器,调用后台接口。
但是现在我在组件jsx文件中调用server中的接口,启动后在浏览器里面去调用该接口,报错如下:
如果直接在浏览器里面输入server接口的url,localhost直接拒绝访问:
server.js代码如下:
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const express = require('express');
const app = express();
// Dev
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, '/../build')));
app.use('/animal', demoRouter); // Express Middleware
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/../build', 'index.html'));
});
app.get('/hell', function (req, res) {
res.send('POST request to the homepage')
})
const port = process.env.PORT || 3005;
app.listen(port);
组件中调用server.js接口的代码如下
axios.get("http://localhost:3005/hell").then((data)=>{
console.log(data)
debugger
this.setState({
name: data.data
})
});
代理配置过,在package.json内配置 "proxy":"http://localhost:3005",我没有起作用。有没有大佬帮忙解释下啊?
你的node.js运行了吗?