2017-02-25 87 views
3

我知道这感觉像是一个重复的问题,但我已尝试所有可能的方式为我的ajax请求工作,但它只是无法。这是ajax代码。 ajax调用是从index.html中的js文件触发的Cors not for XMLhttprequest node/express

self.getJSON =() => { 
     $.ajax({ 
      type: 'POST', 
      url: 'https://iot-backend-metropolia.herokuapp.com/api/user' , 
      contentType: 'application/json; charset=utf-8', 
      dataType: "json", 
     }) 
     .done(function(result) { 
      console.log(result); 
     }) 
     .fail(function(xhr, status, error) { 
      alert(error); 
     }) 
     .always(function(data){ 
     }); 
    } 

我试过2种方法。

1) npm install cors 
app.use(cors()) 
2) // Add headers 
app.use(function (req, res, next) { 

    // Website you wish to allow to connect 
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888'); 

    // Request methods you wish to allow 
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 

    // Request headers you wish to allow 
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); 

    // Set to true if you need the website to include cookies in the requests sent 
    // to the API (e.g. in case you use sessions) 
    res.setHeader('Access-Control-Allow-Credentials', true); 

    // Pass to next layer of middleware 
    next(); 
}); 

这两种方法都失败了,我找遍了网上,但每个人的答案是一样的,现在我就正在发生的事情与我的服务器混淆。

我会发布我的server.js文件,如果有人可以找出最新的错误会有很大的帮助。

const path = require('path'); 
const http = require('http'); 
const express = require('express'); 
const cors = require('cors'); 
var bodyParser = require('body-parser'); 
var cookieParser = require('cookie-parser'); 

const publicPath = path.join(__dirname, '../public'); 
const port = process.env.PORT || 3000; 
var app = express(); 

app.use(cors()) 

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 

app.use(express.static(publicPath)); 

app.listen(port,() => { 
    console.log(`Server is up on ${port}`); 
}); 

错误消息在下面提供。 XMLHttpRequest无法加载https://iot-backend-metropolia.herokuapp.com/api/user。对预检请求的响应不会通过访问控制检查:请求的资源上不存在“访问控制 - 允许来源”标头。因此不允许访问原产地'http://localhost:3000'。

+0

是什么devtools显示的响应头? –

+0

@DanielT。 304未修改 –

回答

0

,你可以补充一点:

app.all('*', function(req, res, next) { 
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); 
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); 

    if (req.method == 'OPTIONS') { 
     res.send(200); 
    } else { 
     next(); 
    } 
}); 
+0

不工作:( –