Javascript 如果我在正文中发送带有json的请求,Cors会发出问题
我在本地主机端口3000上运行react,在端口8000上运行express。 我想从react内部执行以下请求:Javascript 如果我在正文中发送带有json的请求,Cors会发出问题,javascript,reactjs,express,cors,fetch-api,Javascript,Reactjs,Express,Cors,Fetch Api,我在本地主机端口3000上运行react,在端口8000上运行express。 我想从react内部执行以下请求: fetch('http://localhost:8000/login', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(json), //this line cause cors problems }) 但是我得到了以下错误
fetch('http://localhost:8000/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(json), //this line cause cors problems
})
但是我得到了以下错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
如果我从请求中删除主体,请求实际上可以正常工作
这是我的快递服务器
let app = express(); // Export app for other routes to use
let handlers = new HandlerGenerator();
const port = process.env.PORT || 8000;
//middlewares
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
//app.use(cors({origin:'http://localhost:3000'})); //restrict the origin to localhost doesn't work either
app.use( (req, res, next) => {console.log(req.body); next()});
// Routes & Handlers
app.options('/login', (req, res)=>{res.end()});
app.post('/login', handlers.login);
app.get('/', middleware.checkToken, handlers.index);
app.options('/', (req, res)=>{ res.end();} );
app.listen(port, () => console.log(`Server is listening on port: ${port}`));
希望有人能解释一下。
谢谢
Amit移动应用程序。使用(cors())
将其置于其他中间件之上。像这样:
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
在处理请求正文之前,您必须允许使用cors
。移动app。使用(cors())
将其置于其他中间件之上。像这样:
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
在处理请求正文之前,必须允许cors