wot*_*cem 8 javascript console node.js npm reactjs
react/node/使用 npm start 来启动服务器非常新。使用 npm start 启动服务器工作并显示我的反应代码,但我需要做一些调试。但是,我的 console.logs 没有输出到浏览器控制台。在那之后,我想检查我的终端(我认为这是 node console.log 输出到的地方),但由于我使用了 npm start,我启动应用程序的终端卡在这个屏幕上:
Compiled successfully!
You can now view my-app in the browser.
Local: http://localhost:3000/
On Your Network: http://[ip_address_here]:3000/
Note that the development build is not optimized.
To create a production build, use npm run build.
Run Code Online (Sandbox Code Playgroud)
因此,我无法在此屏幕上读取任何控制台输出。我觉得这应该是一个超级基本的修复,我可能只是忽略了一些非常明显的东西,但是有人可以帮我吗?谢谢。
编辑:我被要求分享一些代码,这里是:
这是我的 App.js 文件的一个片段:
import React from 'react';
//quick class
class App extends React.Component {
constructor(props){
super(props);
this.state = {
testRows : null
}
this.getTest = this.getTest.bind(this);
}
//get some rows from my api using a local database with sqlite3
async getTest(){
try{
console.log("hello?");
const response = await fetch('http://localhost:3000/api/test');
if(response.ok){
const JSONresponse = response.json();
console.log(JSOnresponse);
this.setState({testRows : JSONresponse});
}
else{
this.setState({testRows: "test error"});
console.log('There was an error with the fetch');
}
}
catch(error){
console.log(error);
}
}
//render some text, a button, and the result
render(){
let testResults;
if(this.state.testRows){
testResults = Object.keys(this.state.testRows).map((data) => {
return <h1>{data.name}</h1>
}
)
}
else{
testResults = "null";
}
return(
<div>
<h2>Some testing going on here</h2>
<button onClick={this.getTest}>
Press me for test!
</button>
<h3>{testResults}</h3>
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
这是我的 api.js 文件的片段:
apiRouter.get('/test', (req, res, next) => {
db.get('SELECT * FROM Test', (error, rows) => {
if(error){
console.log(error);
}
else{
console.log("got the test");
console.log(rows);
res.send(rows);
}
})
})
Run Code Online (Sandbox Code Playgroud)
路由器已安装,其他所有内容都在代码的其他部分,但那里的 console.logs 也没有出现在任何地方(开发工具控制台或终端)。
据我了解,你有两段代码在不同的地方运行。两者都应该服务才能执行代码。
该App.js文件似乎是一个应该在浏览器上运行的 React 应用程序(前端)。要查看控制台消息,您应该:
npm start另外,尝试将日志放在类声明之后或其他位置,以隔离可能的其他问题。
另一方面api.js是后端代码,因此控制台消息应记录在其运行的终端中。假设您拥有完整的文件api.js而不仅仅是该片段,要运行服务器并查看日志,您应该:
node api.js我会做同样的建议,如果您将日志命令放在脚本的开头,则消息将在服务器启动时显示,而无需转到浏览器。隔离问题是解决问题的好方法。
如果您没有完整的api.js,请尝试一个简单的片段:入门。console.log('Console says hi!')只需在开头添加,或者如果您想在打开浏览器后看到它,则在“Hello World”行之后添加。
最后一点是确保前端和后端不在同一端口 (3000) 上提供服务。