表达app.get (& # 39;/* ')和api CORs问题
express app.get(' /* ') and api CORs issue
你能告诉我如何得到我的json api吗?
server.js
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
})
app.get('/api', function(req, res) {
res.header()
res.json({'message' : 'hi this is my json obj'});
})
App.js
class App extends React.Component {
componentDidMount() {
// let foo;
axios.get('http://localhost:3000/api')
.then(res => {
console.log(res.data);
res.data.message;
})
.catch(err => {
console.log(err);
})
}
由于某种原因,我可以通过输入url字段让react路由器访问localhost:3000/dashboard。它一直返回html字符串。我能改变什么,使它,使我可以接收json对象,而不是html字符串?
您有cors问题,因为您试图从此url http://localhost:3000/api检索数据,这是很正常的。问题是,如果您从另一台服务器(让我们假设apache的端口为80)提供应用程序,那么您也会遇到cors问题。
绕过这个的一种方法是在注册所有路由之前注册一个中间件: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.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
})
app.get('/api', function (req, res) {
res.header()
res.json({ 'message': 'hi this is my json obj' });
})
您可以使用cors模块并像这样注册它,而不是创建自己的中间件:
var cors = require('cors');
app.use(cors());
注意做这样的事情:
res.header("Access-Control-Allow-Origin", "*");
对于您的服务器来说可能有点危险,因为其他应用程序将能够毫无问题地直接从浏览器使用您的API。这是有原因的,我建议研究一下。
编辑
顺便说一下,如果你的api和react应用程序来自同一个节点服务器,那么只需替换这一个:
axios.get('http://localhost:3000/api')
和这个:
axios.get('/api')
应该
你需要改变路由声明的顺序:
app.get('/api', function(req, res) {
res.header()
res.json({'message' : 'hi this is my json obj'});
})
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
})
这是因为/*
将也匹配/api
,而Express的匹配不是基于哪条路由匹配最好,而是基于哪条路由首先匹配。
总是在不太具体的路由之前声明更具体的路由
相关文章:
- 使用YouTube iFrame API的IE中的JavaScript问题
- 可以'由于CORS问题,无法访问Heroku上的Flask API
- HTML5 FileReader API内存问题
- Google 日历 API V3 会解决与会者和创建者 Java 脚本问题
- Firebase API 问题与 AngularJS 网站示例项目
- Chrome 中的 Dropbox Chooser API 问题
- 使用 GitHub API 在 dojo 中执行 PUT 更新会返回 400:解析 JSON 时出现问题
- 使用谷歌方向 API 问题绘制超过 8 个航点的路线图
- USPS使用XMLHttpRequest跟踪API问题
- YouTube在IOS和Android上嵌入API问题
- 谷歌图表API问题
- 《英雄指南》教程中出现的“angular-in-memory-web-api”问题
- Chrome历史API问题
- Edge中的DOM API问题
- Google使用OAuth2身份验证从JavaScript客户端接触API问题
- 历史API问题
- 谷歌地图API问题与地理编码器
- AngularJS:对象、数组、JSON、API问题
- Angular + PHP登录API问题
- Ajax请求维基百科API问题