簡體   English   中英

如果我在正文中發送帶有 json 的請求,Cors 會出現問題

[英]Cors issues if I send request with json in body

我在 localhost 端口 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
  })

但后來我收到以下錯誤:

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

希望有人能解釋一下。 謝謝阿米特

app.use(cors())移至其他中間件之上。 像這樣:

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

在處理請求正文之前,您必須允許cors

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM