[英]send post request for Api in next.js
I am trying to send a request to Exist API using next.js the backend in PHP I am trying to send a post request (Axios)with data and see the response who can I handle this API in my code I read that I need to put some API 文件中的代码,但我不知道怎么做? 除了我的终点,我应该在哪里?
export default Login;
您的 next.js 代码很好,并且您在评论中提到的错误发生在 Axios 库由于 Internet 连接问题、CORS 策略等原因而无法与服务器通信时。
我试过在我的系统上运行你的代码,这就是我在控制台中得到的
我尝试使用 postman 运行 API 调用,它似乎工作正常。 因此,排除了原因 1,您的错误的唯一原因是 CORS,如图所示。
我还用我的 API 调用替换了您的调用,代码似乎可以完美运行。 所以请放心,nextjs 或 Axios 不是问题。
另请注意,如果您愿意将 cookies 发送到域与运行 nextjs 的域不同的服务器,则需要在 axios 中添加 withCredentials: true 。 像这样的东西。
axios.get('url', {withCredentials: true});
解决方案:
允许服务器允许的源上的端口(例如 localhost:3000)访问它。
header('Access-Control-Allow-Origin: *');
要在 PHP 中启用 CORS,请查看此解决方案: 带有 PHP 标头的跨域请求标头(CORS)
希望这可以解决您的问题。 如果仍然没有,请在下面发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.