从react应用程序提取到localhost express服务器时出现cors错误
我的react应用程序在本地主机上运行:3000 我的express服务器在本地主机上运行:1234 这是我的express服务器:从react应用程序提取到localhost express服务器时出现cors错误,express,cors,fetch,Express,Cors,Fetch,我的react应用程序在本地主机上运行:3000 我的express服务器在本地主机上运行:1234 这是我的express服务器: const express = require("express") const cors = require("cors") const app = express(); const PORT = 1234; const spawn = require("child_process").spawn; app.use(cors()) app.listen(PO
const express = require("express")
const cors = require("cors")
const app = express();
const PORT = 1234;
const spawn = require("child_process").spawn;
app.use(cors())
app.listen(PORT, function(){
console.log(`listening on port:${PORT}...`)
})
app.get("/api/play/:choice", function(req,res){
res.status(200).send("lets go")
/*pythonProcess = spawn('python',["./script.py", req.params.choice]);
pythonProcess.stdout.on('data', function(data) {
res.status(200).send(data.toString('utf-8'))})*/
})
我有一个像这样的react应用程序
fetch(`localhost:1234/api/play/${this.state.value}`)
.then(function(res) {
res.text().then(function(text){
console.log(text)
});
})
我在react服务器的控制台中发现此错误:
Fetch API cannot load localhost:1234/api/play/rock. URL scheme must be "http" or "https" for CORS request.
当我使用“邮递员”时,我使用“邮递员”,当我在上使用它时,我会得到正确的响应:
http://localhost:1234/api/play/whatever
在.env文件中(如果有)(根目录) 并使用它
const HOSTNAME = process.env.PFPLUS_API_URL;
fetch(`${HOSTNAME}/api/play/${this.state.value}`)
.then(function(res) {
res.text().then(function(text){
console.log(text)
});
})
如果您不使用env文件方式,请使用这种方式
fetch(`http://localhost:1234/api/play/${this.state.value}`)
如果显示新cors错误,请在express server文件上使用此代码
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});
在.env文件中(如果有)(根目录) 并使用它
const HOSTNAME = process.env.PFPLUS_API_URL;
fetch(`${HOSTNAME}/api/play/${this.state.value}`)
.then(function(res) {
res.text().then(function(text){
console.log(text)
});
})
如果您不使用env文件方式,请使用这种方式
fetch(`http://localhost:1234/api/play/${this.state.value}`)
如果显示新cors错误,请在express server文件上使用此代码
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
next();
});