gpt4 book ai didi

javascript - 请求的资源 : Mean stack 上不存在 'Access-Control-Allow-Origin' header

转载 作者:行者123 更新时间:2023-12-01 01:54:06 26 4
gpt4 key购买 nike

我已经安装了 cors 和 body 解析器。这是我的 authSrvi​​ce.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 控制台中,它显示错误为

Failed to load http://localhost:3000/api/femail: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 400. Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:3000/api/femail with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

在我的cmd中显示为

SyntaxError: Unexpected token m in JSON at position 0 at JSON.parse () at createStrictSyntaxError (E:\project-1\node_modules\body-parser\lib\types\json.js:158:10) at parse (E:\project-1\node_modules\body-parser\lib\types\json.js:83:15) at E:\project-1\node_modules\body-parser\lib\read.js:121:18 at invokeCallback (E:\project-1\node_modules\raw-body\index.js:224:16) at done (E:\project-1\node_modules\raw-body\index.js:213:7) at IncomingMessage.onEnd (E:\project-1\node_modules\raw-body\index.js:273:7) at emitNone (events.js:106:13) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1064:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at 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);
});

我不知道出了什么问题。

最佳答案

The response had HTTP status code 400.

如果服务器抛出错误,添加 Access-Control-Allow-Origin header 不会解决问题。

您需要找出抛出错误的原因。

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

将您自己开发的 CORS 中间件替换为 this standard module它支持预检 OPTIONS 请求。

关于javascript - 请求的资源 : Mean stack 上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com