2017-02-25 5 views
3

これは繰り返しの質問のように感じられますが、私は自分のAjaxリクエストのために可能な限りすべての方法を試しましたが、それはできません。ここにajaxコードがあります。 ajax呼び出しは、index.htmlのjsファイルから起動されます。XMLhttprequestノード/ expressでCorsが動作しない

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を読み込めません。プリフライト要求への応答がアクセス制御チェックを通過しない:要求されたリソースに「アクセス制御許可」がない。 Origin 'http://localhost:3000'はアクセスできません。

+0

? @DanielT。 –

+0

304 Not Modified –

答えて

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

動作しません:( –

関連する問題