所请求的资源上不存在“ Access-Control-Allow-Origin”标头:平均堆栈

时间:2018-07-04 11:29:41

标签: javascript node.js angular express mean-stack

我已经安装了cors和body解析器。这是我的authSrvice.js文件

resetemail(emailid) {
   let headers = new Headers();
   headers.append('Content-Type','application/json');
   return this.http.post('http://localhost:3000/api/femail',emailid,{headers:headers})
   .map(res => res.json());
 } 

这是来自路线文件

const User = require('../models/user');
router.post('/femail',(req,res,next) => {
    const emailid = req.email.body;
    User.getUserByUsername(username, (err, user) => {
      if(err) throw err;
    if(!user){
      return res.json({success: false, msg: 'User not found'});
    }
    else {
      return res.json({success: true, msg: 'success'});
    }
    });
  });

在chrome控制台中,显示为

的错误
  

无法加载http://localhost:3000/api/femail:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。因此,不允许原点“ http://localhost:8100”   访问。响应的HTTP状态码为400。   跨域读取阻止(CORB)阻止了跨域响应   http://localhost:3000/api/femail,MIME类型为text / html。看到   https://www.chromestatus.com/feature/5629709824032768了解更多   详细信息。

在我的cmd中显示为

  

SyntaxError:JSON中位置0处的意外令牌m       在JSON.parse()       在createStrictSyntaxError(E:\ project-1 \ node_modules \ body-parser \ lib \ types \ json.js:158:10)       在解析时(E:\ project-1 \ node_modules \ body-parser \ lib \ types \ json.js:83:15)       在E:\ project-1 \ node_modules \ body-parser \ lib \ read.js:121:18       在invokeCallback(E:\ project-1 \ node_modules \ raw-body \ index.js:224:16)       完成时(E:\ project-1 \ node_modules \ raw-body \ index.js:213:7)       在IncomingMessage.onEnd(E:\ project-1 \ node_modules \ raw-body \ index.js:273:7)       在emitNone(events.js:106:13)       在IncomingMessage.emit(events.js:208:7)       在endReadableNT(_stream_visible.js:1064:12)       在_combinedTickCallback(内部/进程/next_tick.js:138:11)       在process._tickCallback(internal / process / next_tick.js:180:9)

这是我的server.js

    const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
var methodOverride = require('method-override');
var session = require('express-session')
var nodemailer = require('nodemailer');
var async = require('async');
var crypto = require('crypto');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// Connect To Database
mongoose.connect(config.database);
// On Connection
mongoose.connection.on('connected', () => {
    console.log('Connected to database '+config.database);
});

// On Error
mongoose.connection.on('error', (err) => {
    console.log('Database error: '+err);
});

const app = express();
const port = 3000;
//app.use(require('connect').bodyParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const users = require('./routes/users');
app.use('/api',users);
// CORS Middleware
app.use(cors());

// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => { 
    res.send('Invalid endpoint');
});

// Body Parser Middleware


app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
  });

app.use(session({ secret: 'this is a cat' }));  
app.use(cookieParser());
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());

require('./config/passport')(passport);
app.use('/users', users);



app.listen(port, () => {
   console.log("Server started on port:", port); 
});

我不知道怎么了。

2 个答案:

答案 0 :(得分:1)

  

响应的HTTP状态代码为400。

如果服务器引发错误,添加Access-Control-Allow-Origin标头将无法解决问题。

您需要弄清楚为什么会引发错误。

最可能的原因是,通过发布JSON,您正在触发服务器无法处理的预检选项请求。

this standard module替换自己的CORS中间件,该中间件支持预检OPTIONS请求。

答案 1 :(得分:1)

app.use(cors());应该先于所有其他中间件。