node.js - node.js - 从本地客户端调用本地API

我试图从我的React客户端调用我的node api ,两个客户端都在我的机器上,nodeapi在端口8000上运行,react客户端在端口3000上运行,谁可以帮助我?


import React, { Component } from"react";


import axios from"axios";



export class Login extends Component {


 constructor(props) {


 super(props);


 this.state = {


 email:"",


 password:""


 };



 this.change = this.change.bind(this);


 this.submit = this.submit.bind(this);


 }



 change(e) {


 this.setState({


 [e.target.name]: e.target.value


 });


 }



 submit(e) {


 e.preventDefault();


 axios


 .post("http://localhost:8000/api/users", {


 email: this.state.email,


 password: this.state.password


 })


 .then(res => localStorage.setItem("cool-jwt", res.data));


 }



 render() {


 return (


 <div>


 <form onSubmit={e => this.submit(e)}>


 <label>email</label>


 <input


 type="text"


 name="email"


 onChange={e => this.change(e)}


 value={this.state.email}


 />


 <label>password</label>


 <input


 type="text"


 name="password"


 onChange={e => this.change(e)}


 value={this.state.password}


 />


 <button type="submit">Submit</button>


 </form>


 </div>


 );


 }


}



export default Login;




//POST new user route (optional, everyone has access)


router.post('/', auth.optional, (req, res, next) => {


 const {


 body: {


 user


 }


 } = req;



 if (!user.email) {


 return res.status(422).json({


 errors: {


 email: 'is required',


 },


 });


 }



 if (!user.password) {


 return res.status(422).json({


 errors: {


 password: 'is required',


 },


 });


 }



 const finalUser = new Users(user);



 finalUser.setPassword(user.password);



 return finalUser.save()


 .then(() => res.json({


 user: finalUser.toAuthJSON()


 }));


});



使用以下参数从该链接投递给postman:


{


"user": {


"email":"myemailo@email",


"password":"mypassword"


 }


}



我得到:


{


"user": {


"_id":"5d00d9ed47566f7938a91a3d",


"email":"myemailo@email",


"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Im15ZW1haWxvQGVtYWlsIiwiaWQiOiI1ZDAwZDllZDQ3NTY2Zjc5MzhhOTFhM2QiLCJleHAiOjE1NjU1MjA4NzcsImlhdCI6MTU2MDMzNjg3N30.ZG7vzNFoUqj_c3YcrJloeGZiORSRg0N1yVPhAvlejCs"


 }


}



但是,尝试React得到错误500,帮帮我吧?

时间:

你需要阅读- https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

如果你想启用它,你必须通过header添加cors 。

你需要在header响应中添加Access-Control-Allow-Origin,允许所有人(你不应该这么做):

Access-Control-Allow-Origin : *

就像Postman中的POST请求正文,当用axios发送HTTP请求时,你错过了user字段名称,代码应该是:


axios


.post("http://localhost:8000/api/users", {


 user: {


 email: this.state.email,


 password: this.state.password


 }


})



...