'Access-Control-Allow-Origin'标头错误。响应具有HTTP状态代码503

时间:2018-05-14 22:54:02

标签: javascript

我在ExpressJS + MongoDB中构建了一个api。当我从Postman发出get / post请求时,一切正常但是当我从我的javascript文件中请求它时出现错误:503(Service Unavailable)并且在请求时没有'Access-Control-Allow-Origin'标题资源。因此,不允许原点“http://127.0.0.1:5500”访问。响应的HTTP状态代码为503。

我的javascript文件:

function add_score(user,level,score){
  
  let xmlhttp = new XMLHttpRequest();
  const url = "http://tranquil-mountain-64247.herokuapp.com/api/scores";

  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log("sim");
    }
  };
  xmlhttp.open("POST", url, true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("user="+user+"&level="+level+"&time="+score);
}

我的api文件:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

app.use(bodyParser.json());

mongoose.connect("mongodb://...");

app.get('/api/scores', (req,res) => {
    Score.getScores((err, scores) => {
        if (err){
            throw err;
        }
        res.json(scores);
    })

});

app.post('/api/scores', (req, res) => {
	var score = req.body;
	Score.addScore(score, (err, score) => {
		if(err){
			throw err;
		}
		res.json(score);
	});
});

1 个答案:

答案 0 :(得分:0)

将CORS标头添加到从express / api返回的响应中。

https://enable-cors.org/index.html

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();
});