表达app.get('/ *')和api CORs问题

时间:2016-10-04 05:20:13

标签: javascript json node.js express

你可以告诉我怎样才能得到我的json api吗?

server.js

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, Exception {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out=response.getWriter();

        String sent=request.getParameter("INPUT_TEXT");
        sent=sent.trim();
        NewJFrame2 njf=new NewJFrame2();  
        String p=njf.read(sent);

        Map m1 = new HashMap(); 
         m1.put("x", sent);
         m1.put("y", p);

        Gson gson = new Gson();
        String json = gson.toJson(m1);
        System.out.println(json);
        out.write(json);
        out.close();
    }

App.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'});
})

出于某种原因,我可以通过输入url字段让反应路由器访问localhost:3000 / dashboard。它一直在返回html字符串。我可以改变什么来使我能够接收json对象而不是html字符串?

2 个答案:

答案 0 :(得分:3)

您有问题因为您正在尝试从此网址http://localhost:3000/api检索数据,这很正常。问题是如果你从另一台服务器上提供你的应用程序(让我们为apache假设80端口),你也可以解决这个问题。

绕过这一点的一种方法是在注册所有路由之前注册中间件:

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而不会出现问题。有一个原因是cors到位,我建议研究它。

<强> 修改

顺便说一句,如果你从同一个节点服务器上提供你的api和你的反应应用程序,那么只需替换它:

axios.get('http://localhost:3000/api')

这一个:

axios.get('/api')

应该有效

答案 1 :(得分:3)

您需要切换路线声明的顺序:

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,而且根据哪条路线与最佳,但哪条路线首先与匹配

始终在不太具体的路线之前声明更具体的路线。