除了在nodejs里面的路由请求中设置外
res.set('Access-Control-Allow-Origin', '*');
对于使用creat-react-app构建的项目
1、npm run eject
将当前位置抛出,让我们可以修改配置文件
2、在package.json中添加
"proxy":"http://localhost:后台服务器名称"
3、将网络请求的路径修改
去掉http://120.0.0.1; 直接写nodejs中的路由名
代码示例:
package.json文件:
"proxy":"http://localhost:3000"
网络请求文件:
import React ,{Component}from 'react';
import User from './user'
class App extends React.Component {
constructor()
{
super();
}
componentDidMount()
{
var flag=true;
if(flag)
{
fetch('/news')
.then(data=>{return data.json()})
.then(res=>{console.log(res)})
}else{
fetch('/movie',{
method:'POST',
headers:{
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:"id=jeff"
}).then(data=>{return data.json()})
.then(res=>{console.log(res)})
}
}
render(){
return (
<div className="App">
<User />
</div>
);
}
}
export default App;
nodejs文件:
var express=require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//创建服务器
var app=express();
//开启服务器并监听端口
app.listen(3000,function(){
console.log('this express server is running at http://127.0.0.1:3000 ');
})
app.get('/', function (req, res, next) {
});
app.get('/news', function (req, res, next) {
// res.set('Access-Control-Allow-Origin', '*');
var news = {
id: 1,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='
};
res.json(news);
});
app.post('/movie',urlencodedParser, function (req, res, next) {
// res.set('Access-Control-Allow-Origin', '*');
var id=req.body.id;
var news = {
id: id,
title: 'news title1...',
content: 'news content1...',
commentsUrl: '/comments?newsId='
};
res.json(news);
});
module.exports=app;